5

I have an exception which gives me error from form like::

except ValidationError as e:
    return JsonResponse(e, safe=False)

It is giveing me the error ValidationError({'age': [u'This field is required.'], 'name': [u'This field is required.']}) is not JSON serializable

Why I am getting this error and how can I make it work .. Any idea ??

4
  • 1
    If you're using a form then why not let the form handle the validation as normal? Please try to show a minimal reproducible example Commented Apr 21, 2016 at 10:28
  • @Sayse I am posting the from form ajax so I want to send the error as response.. Commented Apr 21, 2016 at 10:38
  • 1
    Don't know why you @ -ed me. But still, Sayse's point is still valid; the form collects the validation errors into an error list, and it's that that you should be serializing. Don't return responses from inside form methods, in any case. Commented Apr 21, 2016 at 10:40
  • Yes it is giving me validatation errors in list but it is not being serialized. How come ? Commented Apr 21, 2016 at 10:45

3 Answers 3

3

Your e is an instance of ValidationError, not a dict. In order to access the message details you can use the .message_dict property:

return JsonResponse(e.message_dict, safe=False)
Sign up to request clarification or add additional context in comments.

3 Comments

It is giving me error dict object is not callable
thanks man.. worked like a charm.. one question.. I have tried this too # response = serializers.serialize('json', e) return JsonResponse(response, safe=False) and why it didn't worked. It is supposed to serialize this right ?
Again, your e variable is not serializable. So no, this is normal behavior.
1

You can use this

https://docs.djangoproject.com/en/2.0/ref/forms/api/#django.forms.Form.errors.as_json

as simple as:

except ValidationError as e:
  return e.as_json

Comments

0

For me given answers didn't work. I've solved it by using ValidationError method get_full_details().

except ValidationError as e:
    return JsonResponse(e.get_full_details(), safe=False)

Comments

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.