Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning pure Django form errors in JSON

I have a Django form which I'm validating in a normal Django view. I'm trying to figure out how to extract the pure errors (without the HTML formatting). Below is the code I'm using at the moment.

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

With this, I get the infamous proxy object error from Django. Forcing each error into Unicode won't do the trick either, because then each of the errors' __unicode__ method will be called effectively HTML-izing it.

Any ideas?

EDIT:

For those interested, this is the definition of json_response:

def json_response(x):
    import json
    return HttpResponse(json.dumps(x, sort_keys=True, indent=2),
                        content_type='application/json; charset=UTF-8')
like image 289
Deniz Dogan Avatar asked Jun 12 '09 12:06

Deniz Dogan


2 Answers

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.

like image 121
SystemParadox Avatar answered Nov 11 '22 22:11

SystemParadox


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)
like image 34
lampslave Avatar answered Nov 12 '22 00:11

lampslave