以下代码显示了我的模板,视图和表单代码。当重新呈现html表单时,我想显示由views.py中调用的.is_valid()函数生成的错误。问题是我什至无法访问events_form和events_formset中的错误,更不用说显示它们了。事件_form.errors,事件_formset.errors或
{% for field in incident_form %}
{% for error in field.errors %}
<p> {{ error }} </p>
{% endfor %}
{% endfor %}
允许我查看由.is_valid方法生成的错误。奇怪的是,香脆的应用程序返回到无效表单,突出显示了第一个无效字段,并准备接受用户的输入。另外,当日期字段填写不正确时,表格有时会 显示错误,例如“无效的日期字段”。但是,没有数据提交的必填字段都不会显示“必填”错误。非常感谢您的帮助。
new_incident.html的片段:
<form method="post" class="form-horizontal">
{% crispy incident_form %}
<input type="button" id="delete_field_data" class="btn btn-outline-danger" value="Delete Field Incident Data">
<div id="form_set_class">
{{ incident_formset.management_form }}
{% for form in incident_formset %}
{{form.non_field_errors}}
{{form.errors}}
{% crispy form %}
{% endfor %}
</div>
[...]
forms.py的片段:
class IncidentForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(IncidentForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_tag = False
self.helper.layout = Layout( [<edited_out_for_this_post] )
self.helper.form_id = "incident_form"
class PartDeficiencyForm(forms.ModelForm):
class Meta:
model = PartDeficiency
fields = "__all__"
DeficiencyFormSet = modelformset_factory(model=PartDeficiency, form=PartDeficiencyForm, exclude=None, extra=0, max_num=20, can_delete=True)
views.py的片段:
def new_incident(request):
if request.method == 'POST':
incident_form = IncidentForm(request.POST)
deficiency_formset = DeficiencyFormSet(request.POST)
if incident_form.is_valid() and deficiency_formset.is_valid():
incident_form.save()
deficiency_formset.save()
return redirect('quality_dept:home')
else:
dict = {'incident_form': incident_form, 'incident_formset': deficiency_formset}
return render(request, 'incidents/new_incident.html', dict)
else:
incident_form = IncidentForm()
formset_data = { 'form-TOTAL_FORMS': '0',
'form-INITIAL_FORMS': '0',
'form-MAX_NUM_FORMS': '20'}
def_formset = DeficiencyFormSet(formset_data)
dict = {'incident_form': incident_form, 'incident_formset': def_formset}
return render(request, 'incidents/new_incident.html', dict)