我正在使用 earle / django-bootstrap 来展示一个带有 twitter bootstrap 样式的表单。我希望能够更改样式并显示用户在填写表单时犯的错误(即,如果他错过了必填字段)
我在文档中找不到有关如何输出错误的信息。我正在使用 jquery.form.js 提交表单并在字典中的数组中返回错误,问题是错误数组返回空,甚至在视图中打印错误数组也显示它为空。
表格的代码:
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, )
以及视图的代码:
@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))
还有 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);
}
}