I am working with Django and Ajax. With the help of jQuery, i successfully sent form data to server and able to validate it.
Problem arrive when form is invalid, i want that, if the form is invalid, ajax get the invalid form and render it to same template with errors like all invalid forms do.
How Can i do it?
The closest method you can do is to return Form.errors . For example:
def submitSample(request):
form = SampleForm(request.POST)
response_data = {}
if form.is_valid():
form.save()
response_data['result'] = 1
else:
response_data['result'] = 0
response_data['errors'] = form.errors
return HttpResponse(response_data)
The response_data['errors']
will contain a dictionary of error messages like:
{'title':['This field is required.']}
After sending the ajax request, you can use jQuery to display the errors on the form elements. Note that you will have to find a way to append the error messages next to their elements.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.