views.pyclass SomeFormHandler(FormView):
def form_invalid(self, form):
if self.request.is_ajax():
data = {'status': 'error', 'erros': []}
for field, errors in form.errors.items():
for error in errors:
data['errors'].append({'key': field, 'desc': error})
return JsonResponse(data)
else:
...
script.js (Bootstrap + jQuery)
$.post($(form).attr('action'), $(form).serialize(), function(result) {
if(result.status == 'ok') {
form.reset();
showAlert('Сообщение успешно отправлено', 'success');
}
else if(result.status == 'error') {
for(var ndx in result.errors) {
if(result.errors[ndx].key == '__all__') showAlert(result.errors[ndx].desc);
$(form).find('[name=' + result.errors[ndx].key + ']').parent().addClass('has-error');
}
}
}).fail(function(xhr, textStatus, error) {
showAlert('Ошибка отправки сообщения');
});