Django Rest Framework combine field and non field errors

Viewed 96

I have a model serializer for changing the email and password.

class ChangeEmailSerializer(ModelSerializer):
    class Meta:
        model = CustomUser
        fields = ['email', 'password']
        
    def update(self, instance, validated_data):
        instance.email = validated_data.get('email')
        return super().save_instance(instance)

How do I combine the a field error from EmailField with a non field error from the validate function used to check the user password?

1 Answers

You can write a custom validator and use it in your model. Below I added the simple example using function based validator.

Validator:

def email_valid(email):
    if '@' not in email:
        raise serializers.ValidationError('This field must contain a proper email.')

Model:

class CustomUser(AbstractUser):
    # ...

    email = models.EmailField(_('email address'), validators=[email_valid])
Related