Django Rest Framework Custom Validation Errors

I am trying to configure default validation errors for DRF (3.x) for an account model. My goal is to write a validation function to send a customized error message.

I tried the following:

class AccountSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True, required=False)

    class Meta:
        model = Account
        fields = ('id', 'email', 'password',)

    def validate_password(self, value):
        """
        Validate Password.
        """
        if not value:
            raise serializers.ValidationError("Password cannot be empty!")
        elif len(value) < 5:
            raise serializers.ValidationError("Password to short...")
        return value

Checking the length works fine, but the "password is empty" is never thrown because the default error ("password", [u'This field cannot be empty.]]). >

Is there an option to disable default errors or force verification using my custom function?

Thanks for the help!

+4
source share
2 answers

, error_messages . , , - , .

: required min_length. blank, , allow_blank=True .

,

class AccountSerializer(serializers.ModelSerializer):
    password = serializers.CharField(
        write_only=True,
        required=False,
        min_length=5,
        error_messages={
            "blank": "Password cannot be empty.",
            "min_length": "Password too short.",
        },
    )

    class Meta:
        model = Account
        fields = ('id', 'email', 'password', )

len min_length .

Django REST, . - validate_password, , , .

+5

:

to_internal_value, ( ):

:

class AccountSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True, required=False)

    class Meta:
        model = Account
        fields = ('id', 'email', 'password',)

    def to_internal_value(self, data):
        password = data.get('password')
        """
        Validate Password.
        """
        if not password:
            raise serializers.ValidationError({'password': 'Password cannot be empty!'})
        elif len(password) < 5:
            raise serializers.ValidationError({'password': 'Password to short...'})

        return {
            'password': password
        }

, -:)

+1

All Articles