Returning pure Django form errors in JSON Returning pure Django form errors in JSON json json

Returning pure Django form errors in JSON


This appears to have been improved. The following works in Django 1.3:

return json_response({    'success': False,    'errors': dict(form.errors.items()),})

No need for __unicode__ or lazy translation any more. This also gives a full array of errors for each field.


For Django 1.7+ use Form.errors.as_json() or something like this:

errors = {f: e.get_json_data() for f, e in form.errors.items()}return json_response(success=False, data=errors)


Got it after a lot of messing around, testing different things. N.B. I'm not sure whether this works with internationalization as well. This also takes the first validation error for each field, but modifying it to get all of the errors should be rather easy.

return json_response({ 'success' : False,                       'errors' : [(k, v[0].__unicode__()) for k, v in form.errors.items()] })