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?
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.
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})
Not being picky here but did you actually validate your form ?
form.is_valid()
精彩评论