I\'m trying to create a page with two functional parts:
Why not return JSON with validation errors when form contains invalid data? Django has a Form.errors fields which contains validation errors for each field. These field can easily be converted to JSON and used to mark your inputs invalid:
Your view:
def submit_form_view(request):
if request.method == 'POST': # If the form has been submitted...
form = ChartForm(request.POST)
if form.is_valid(): # All validation rules pass
# Return JSON response if form was OK
response_data = {'form_saved':True, 'data':'somedata'}
return HttpResponse(json.dumps(response_data), mimetype="application/json")
else: # Invalid data:
# Send what were errors
response_data = {'form_saved': False, 'errors': form.errors}
return HttpResponse(json.dumps(response_data), mimetype="application/json")
else:
form = ChartForm() # An unbound form
return render_to_response('contact.html', {
'form': form,
})
Javascript code:
$.ajax({
url: '{% url someapp.submit_form_view %}',
success: function(data) {
if( data.form_saved ){
$('#form input').removeClass('error'); // Form submit ok -> remove error class of all fields
var chart_data = data.chart_data;
// Update the chart here
}else{
var form_errors = data.form_errors;
// Display form validation errors
for(var fieldname in form_errors) {
var errors = form_errors[fieldname]; // Array of error strings for fieldname
$('#form input[name="'+fieldname+']').addClass('error')
}
}
}
});