Sussagittikasusa
Sussagittikasusa

Reputation: 2581

How to serialize dictionary in django to render in Jquery [Level of question - Beginner]

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?

Upvotes: 1

Views: 1083

Answers (3)

Auston
Auston

Reputation: 478

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.

Upvotes: 3

Davo
Davo

Reputation: 221

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

form.is_valid()

Upvotes: 0

Tom Gruner
Tom Gruner

Reputation: 9635

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})

Upvotes: 0

Related Questions