1

Hi I have the following dict to be serialised

{
    "field_name":"myrole",
    "description":"it has access",
    "status":"active",
    "role":"admin",
    "modules":[
        {
          "module_id":"newid",
          "create":true,
          "read":true,
          "update":true,
          "delete":true
        }
]

}

Serializer I'm having now is

class ModulerSerializer(serializers.Serializer):
    module_id = serializers.BooleanField(required=True, allow_null=True)
    delete = serializers.BooleanField(required=True)
    read = serializers.IntegerField(required=True)
    create = serializers.BooleanField(required=True)
    update = serializers.BooleanField(required=True)


class RoleValidateSerializer(serializers.Serializer):
    field_name = serializers.BooleanField(required=True)
    description = serializers.CharField(required=True, max_length=128)
    role = serializers.CharField(required=True, max_length=128)
    status = serializers.CharField(required=True, max_length=128)
    modules = serializers.ListField(child=ModulerSerializer())

it is producing the error message like below

{'field_name': [ErrorDetail(string='Must be a valid boolean.', code='invalid')], 
  'modules': {
          0: {'module_id': [ErrorDetail(string='Must be a valid boolean.', code='invalid')], 
'read': [ErrorDetail(string='A valid integer is required.', code='invalid')]}}}

What I'm expecting is to append all error message values in to a single array like below or extracting error message from all nested child object

[field_name Must be a valid boolean,module_id Must be a valid boolean, read A valid integer is required.  ]

1 Answer 1

4

An option is to define your custom exception handler that will be used in any web service call: create a python file (e.g., handle_exceptions.py) under your django application, let app, and put the logic on it.

For instance:

app/handle_exceptions.py

import copy
from rest_framework.exceptions import ValidationError
from rest_framework.views import exception_handler

def my_exception_handler(exc, context):
  response = exception_handler(exc, context)

  if response is not None:
    try:
      if isinstance(exc, ValidationError):
        custom_errors = []
        errors = copy.deepcopy(response.data)
        for field, message in errors.items():
          if isinstance(message, dict):
            # process message
            # error_message = '...'
          elif isinstance(message, list):
            # process message
            # error_message = '...'
          elif isinstance(message, str):
            # process message
            # error_message = '...'
          custom_errors.append(error_message)        

        response.data = custom_errors
    except Exception as ex:
      print(str(ex))
    return response  

To get the str representation of the ErrorDetail(string='Must be a valid boolean.', code='invalid') try str(ErrorDetail(string='Must be a valid boolean.', code='invalid')).

Then, go to the your project settings and change the EXCEPTION_HANDLER module of the django rest framework as follows:

settings.py

REST_FRAMEWORK = {
    ...

    'EXCEPTION_HANDLER': 'app.handle_exceptions.my_exception_handler'
    # 'EXCEPTION_HANDLER':'rest_framework.views.exception_handler',
}

The above solution requires the usage of django rest framework package.

Sign up to request clarification or add additional context in comments.

1 Comment

What exactly are you doing to the message if it's a dict? ideally wouldn't you want to return the dict?

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.