0

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 ?

Verma
  • 173
  • 9

1 Answers1

0

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.