Pritam Kadam
Pritam Kadam

Reputation: 3285

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."
        ]
}

Upvotes: 0

Views: 4928

Answers (2)

athanasp
athanasp

Reputation: 233

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

Upvotes: 1

Krishna Singhal
Krishna Singhal

Reputation: 661

Yes you can, you have to check if serializer is not valid, then using for loop iterate key of error_dict and append value in list and return list

serializer = YourSerializer(data={"email":"[email protected]", "phone_number": "1234566"})
if serializer.is_valid():
    serializer.save()
else:
    error_list = [serializer.errors[error][0] for error in serializer.errors]
    return Response(error_list)

Upvotes: 3

Related Questions