我正在使用earle / django-bootstrap来显示使用twitter bootstrap设计的表单。我希望能够在填写表单时更改样式并显示用户提交的错误(即,如果他错过了必填字段)
我在文档中找不到如何输出错误。我使用jquery.form.js提交表单并在字典中的数组中返回错误,问题是,errors数组返回为空,甚至在视图中打印errors数组显示为空。
表单的代码:
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);
}
}
答案 0 :(得分:1)
表单的错误在err ['casos']里面,而不是在err里面。祝你有美好的一天