5

Default validation error message given by DRF is a list of key and message. What would be the best way customise this format to a text format. For Example.

This is the default format.

{
"message": {
    "phone": [
        "customer with this phone already exists."
    ],
    "email": [
        "customer with this email already exists."
    ],
    "tenant_id": [
        "customer with this tenant id already exists."
    ]
},
"success": false,
"error": 1
}

This is something what I want.

{
"message": "customer with this phone already exists, customer with this 
email already exists, customer with this tenant id already exists"
"success": false,
"error": 1
}
Arpit Sethi
  • 116
  • 2
  • 9

3 Answers3

1

so to answer this question i did a walk around overriding django rest framework default exception handler like so.

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:

        if isinstance(response.data, dict):
            for data_key, data_array in response.data.items():
                if not (isinstance(data_array, list) and len(data_array) < 2):
                    continue
                if hasattr(data_array[0], "title"):
                    response.data[data_key] = data_array[0].title()

        response.data["status_code"] = response.status_code
    return response

i think there is a reason why django rest make the error for each field a list if i am correct (not really sure tho). i think maybe sometimes a field might happen to have more than one error but i eventually customize it so if its just an error for a field you'll have the custom otherwise a list for multiple errors.

to finish up add the path to this function in dot notation to settings.py (rest_framework settings context) like so

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'myapp.mymodule.custom_exception_handler'
}

in my case i created the function in a module in same package directory as settings.

example: for user already exist and email aready exist you should get a response

{
    "email": "User With This Email Already Exists.",
    "phone": "User With This Phone Already Exists.",
    "status_code": 400
}

happy hacking :)

goodnews john
  • 431
  • 4
  • 9
0

It is common practice, that you display validation messages for individual fields instead of providing single general message. So default behaviour of DRF is follow this convention.

To achieve what you want, you need to create object level validation for your serializer http://www.django-rest-framework.org/api-guide/serializers/#object-level-validation and prevent default behaviour of fields validation.

Zada Zorg
  • 2,778
  • 1
  • 21
  • 25
0

You can change your errors according to your form in views at the time you will give the response serializer.errors instead of that you can pass your own dictionary to that