0

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."
        ]
}
1
  • afaik, no way to do that, because it how DRF implemented. Commented Jan 6, 2021 at 8:06

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

How can I return only a single message? Suppose my serializer returns 3 errors as arrays. I need to send only one, as a string, not an array. Can you provide an example?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.