1

The dictionary to serialize - form.errors

e.g. view -

form = PersonalForm(request.POST)
# errors = serializing function which serializes form.errors
data = errors 
#Is this the way to pass data? Not quite sure....
return HttpResponse(data,mimetype="application/json")

e.g. javascript (on success of request) -

function(responseData) {
     $('#errors_form').html(responseData);
                },

Now how do I do this my friends?

Sussagittikasusa
  • 2,525
  • 9
  • 33
  • 47

3 Answers3

3
import json

data = json.dumps(errors)

return HttpResponse(data,mimetype="application/json")

You're asking how to turn a dictionary into a JSON object, so your jQuery/javascript can read it. json.dumps allows this to happen.

Auston
  • 480
  • 1
  • 6
  • 13
  • As one "should" search for similar questions before asking, I think one should also search before answering a question :) Your answer is a sub-optimal duplicate of this one -> http://stackoverflow.com/questions/986406/returning-pure-django-form-errors-in-json – Tommaso Barbugli Mar 21 '11 at 11:11
  • 1
    So you're saying I should NOT have answered this question because another person answered a similar question? That does not make sense to me. – Auston Apr 21 '11 at 19:11
0

You will need to look in two places for errors.

There are "Non field errors":

form.non_field_errors

And field based errors, for example the name field:

form.name.errors

Depending on the complexity of the form, you could reference the errors as individual errors in your json, or make a small python script that combined them. I didn't actually run the code, but think this could work for you:

errors = []
errors = errors + form.non_field_errors

for field in form:
    errors = errors + field.errors

if len(errors) > 0 :
    data = json.dumps({"response_text": "Errors Detected", "errors" : errors})
Tom Gruner
  • 9,635
  • 1
  • 20
  • 26
0

Not being picky here but did you actually validate your form ?

form.is_valid()
Davo
  • 221
  • 1
  • 4