[Django]-Unable to change validate field error message in Model serializer

5👍

You can define extra_kwargs in the class Meta of your serializer to customize error messages.
https://www.django-rest-framework.org/api-guide/serializers/#additional-keyword-arguments

In your case, you would add this to BlogSerializer:

    extra_kwargs = {
        'title': {
            'error_messages': {
                'blank': 'my custom error message for title'
            }
        }
    }

The tricky part might be figuring out the key you need to override. Getting the errors raised by the validators in the serializer can be done in the django shell. For example.

serializer = BlogSerializer(data={'title':''})
serializer.is_valid()
serializer._errors

{'status': [ErrorDetail(string=u'This field is required.', code=u'required')]
 'title': [ErrorDetail(string=u'This field may not be blank.', code=u'blank')
 'user': [ErrorDetail(string=u'This field is required.', code=u'required')]}

ErrorDetail.code is the key for the error_messages dictionary. In this case, it is ‘blank’.

Leave a comment