Arun SS
Arun SS

Reputation: 1911

Django rest framework: How to change error response format globally

All the error messages return from django default validators ends with a dot (.). Is there anyway to remove that last dot from all messages globally.

Or, If someone help me to find a way to catch these error returning function, I can trim the last dot if exists in that section.

Sample error messages.

{
  "email": [
    "This field may not be blank."
  ]
}


{
  "email": [
    "Enter a valid email address."
  ]
}

Upvotes: 4

Views: 3577

Answers (3)

jnowak
jnowak

Reputation: 705

In settings.py:

import inspect
from rest_framework import fields, relations

DEFAULT_ERROR_MESSAGES = {
    'required': 'CANT_BE_EMPTY',
    'does_not_exist': 'DOES_NOT_EXIST',
    'invalid': 'INVALID_INPUT',
}

modules_with_drf_fields = [fields, relations]
for module in modules_with_drf_fields:
    for name, obj in inspect.getmembers(module):
        if inspect.isclass(obj) and issubclass(obj, fields.Field):
            obj.default_error_messages.update(DEFAULT_ERROR_MESSAGES)

All DEFAULT_ERROR_MESSAGES keys:

required
does_not_exist
invalid
blank
max_length
min_length
invalid_choice
datetime
date
make_aware
overflow
max_value
min_value
max_digits
max_decimal_places
max_whole_digits
max_string_length
not_a_dict
empty
null
no_name
invalid_image
not_a_list
invalid_unicode
no_match
incorrect_match
incorrect_type

Upvotes: 0

Mohammad Mustaqeem
Mohammad Mustaqeem

Reputation: 1084

You can use Restframework's exception handler. Please have a look.

Upvotes: 6

Linovia
Linovia

Reputation: 20976

If you want to change all of them, you should override the field's default messages somewhere in the application initialization:

serializers.CharField.default_error_messages['blank'] = 'This field may not be blank'

For example, the blank message can be found here

Upvotes: 5

Related Questions