gamer
gamer

Reputation: 5863

Python validation error object is not json serializable

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 ??

Upvotes: 4

Views: 7730

Answers (3)

Mylyanyk Marko
Mylyanyk Marko

Reputation: 11

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)

Upvotes: 0

Despota
Despota

Reputation: 175

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

Upvotes: 1

Selcuk
Selcuk

Reputation: 59184

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)

Upvotes: 3

Related Questions