I am using earle / django-bootstrap to show a form styled with twitter bootstrap. I want to be able to change the style and show the errors the user committed while filling the form (i.e. if he missed a required field)
I cannot find in the documentation on how to output errors. I am submitting the form using jquery.form.js and returning errors in an array in a dictionary, the problem is, the errors array returns empty, and even printing the errors array in the view shows it empty.
The code for the form:
class SomeForm(BootstrapForm):
class Meta:
layout = (
Fieldset( "Form title:","first_field", "second_field", ),
)
first_field = forms.CharField(label=u'Some Text', max_length=50, error_messages={'required':u'The error msg',},required=True,)
second_field = forms.ModelChoiceField(label=Some Text', queryset=SomeClass.objects.all(), error_messages={'required':u'The error msg. ',}, required=True, )
And the code for the view:
@login_required
def new_case(request):
if request.method == 'POST':
form = SomeForm(request.POST)
if form.is_valid():
new_case = form.save(request.user)
return HttpResponseRedirect('/casos/')
else:
response_dict = {'ok': False, 'msg': None, 'err': None,}
err = {}
caseErrors = {}
caseErrors.update(form.errors)
for field in caseErrors:
caseErrors[field] = [unicode(error) for error in caseErrors[field]]
err['caso']=caseErrors
response_dict['msg'] = u'The fields are not valid.'
response_dict['err'] = err
return HttpResponse(simplejson.dumps(response_dict), mimetype='application/json')
else:
form = SomeForm()
return render_to_response('casos/new_case.html', { 'form': form }, context_instance=RequestContext(request))
Also the jQuery
<script type="text/javascript" src="{{ STATIC_URL }}jquery/jquery.form.js"></script>
<script type="text/javascript">
$(function() {
$('#agr_ncaso').ajaxForm({
dataType: 'json',
beforeSubmit: before_submit,
success: success
});
});
function before_submit(formData, jqForm, options) {
$('.error').removeClass('error');
$('.alert-error').remove();
return true;
}
function success(json) {
if (json.ok) {
window.location = '/casos/';
}
else if (json.err) {
$('<div class="alert alert-error"><strong>Error inform </strong></div>').insertBefore('form')
for (campo in json.err) {
$('#div_id_' + campo).addClass("error");
}
$('.alert').fadeIn('slow');
}
else {
alert(json.msg);
}
}
The errors of the form are inside err['casos'], not inside err. Have a great day