[Django]-How to change "This field is required" error message for a DjangoRestFramework serializer?

8👍

You can override the __init__() method of UserSerializer to change the default error message for a required field .

We will iterate over the fields of the serializer and change the value of default error_messagesvalue for the required key.

class UserSerializer(SetCustomErrorMessagesMixin, serializers.ModelSerializer):

    def __init__(self, *args, **kwargs):
        super(UserSerializer, self).__init__(*args, **kwargs) # call the super() 
        for field in self.fields: # iterate over the serializer fields
            self.fields[field].error_messages['required'] = '%s field is required'%field # set the custom error message

    ...

1👍

For a ModelSerializer I usually just use the extra_kwargs property, which I find to be much more readable and maintainable. See the below example serializer on how it can be done.

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = '__all__'
        extra_kwargs = {
            "email": {
                "error_messages": {
                    "required": "User's Email is required",
                },
            },
            "phone": {
                "error_messages": {
                    "required": "User's Phone is required",
                },
            },
        }

In the above example email and phone are two fields that exist in the User model. Now instead of the generic ‘This field is required’ message you get custom messages.

Leave a comment