Search code examples
djangodjango-rest-frameworkdjango-serializer

Django rest framework serializer validation error messages in array


Is there a way to get array of error messages instead of object when retrieving validation errors from serializers?

For example:

[
        "User with this email already exists.",
        "User with this phone number already exists."
]

Instead of:

{
        "email": [
            "User with this email already exists."
        ],
        "phone_number": [
            "User with this phone number already exists."
        ]
}

Solution

  • If you want to handle the exceptions in any serializer of your application in the way you mentioned, you can write your own custom exception handler under your application directory (e.g. my_project/my_app/custom_exception_handler):

    from rest_framework.views import exception_handler
    
    def custom_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 response is not None:
            # Place here your code
            errors = response.data
            ...
    
            # return the `response.data`
            # response.data['status_code'] = response.status_code
        return response
    

    After that update the EXCEPTION_HANDLER value in your settings.py:

    REST_FRAMEWORK = {
        'EXCEPTION_HANDLER': 'my_project.my_app.custom_exception_handler'
    }
    

    Checkout more details in the DRF docs