Search code examples
djangodjango-rest-frameworkdjango-serializerdjango-validation

How to change serializer field name when validation error is triggered


I need to change the view of the error displayed when I validate the field.

serializer.py

class ElementCommonInfoSerializer(serializers.ModelSerializer):

    self_description = serializers.CharField(required=False, allow_null=True,
                                             validators=[RegexValidator(regex=r'^[a-zA-Z0-9,.!? -/*()]*$',
                                                                        message='The system detected that the data is not in English. '
                                                                                'Please correct the error and try again.')]
                                             )
    ....

    class Meta:
        model = Elements
        fields = ('self_description',......)

This error is displayed

{
    "self_description": [
        "The system detected that the data is not in English. Please correct the error and try again."
    ]
}

The key of error dict is field name - self_description. For FE I need to send another format like:

{
    "general_errors": [
        "The system detected that the data is not in English. Please correct the error and try again."
    ]
}

How to change this?


Solution

  • One way this could be achieved is via custom exception handler

    from copy import deepcopy
    from rest_framework.views import exception_handler
    
    
    def genelalizing_exception_handler(exc, context):
        # Call REST framework's default exception handler first,
        # to get the standard error response.
        response = exception_handler(exc, context)
    
        # Now add the HTTP status code to the response.
        if 'self_description' in response.data:
            data = deepcopy(response.data)
            general_errors = data.pop('self_description')
            data['general_errors'] = general_errors
            response.data = data
    
        return response
    

    in settings

    REST_FRAMEWORK = {
        'EXCEPTION_HANDLER': 'my_project.my_app.utils. genelalizing_exception_handler'
    }