问题描述(Django 1.7): -
-
呈现包含输入字段和一些模板变量的简单表单 . 模板变量在支持视图中设置,并显示一些样板法律文本 .
-
我有一个自定义的“干净”方法,它检查输入字段值并根据需要设置验证错误 .
-
如果发生错误,表单将通过错误的字段重新显示正确的错误消息 .
但是,模板变量丢失了,即
{}表示最初呈现表单时,如果重新呈现表单以显示错误,则不会设置 .
我理解为什么会发生这种情况,但是有人可以建议我如何在clean方法中重置模板变量,以便按预期工作吗?
这是代码: -
views.py
def form1(request):
legal_text = "Some long legal paragraph ...."
if request.method == 'POST':
form = form1(request.POST)
# do stuff with the posted values ...
else:
form = form1()
return render(request,'form11.html', {'form': form, 'legal_text': legal_text})
forms.py
class form1(forms.Form):
# form contains lots of input questions 'q1', 'q2' etc that are cross-validated
def clean(self):
cleaned_data = super(form1,self).clean()
if not cleaned_data.get('q1'):
self._errors['q1'] = 'Please provide a selection'
if not cleaned_data.get('q2'):
self._errors['q2'] = 'Please provide a selection'
Q1_CHOICES = (('10', 'Yes',), ('01', 'No',),)
q1 = forms.ChoiceField(required=False,label="This is question 1",help_text="Some arbitrary help text",widget=forms.RadioSelect,choices=Q1_CHOICES)
Q2_CHOICES = (('10', 'Yes',), ('01', 'No',),)
q2 = forms.ChoiceField(required=False,label="This is question 1",help_text="Some arbitrary help text",widget=forms.RadioSelect,choices=Q2_CHOICES)
# more questions omitted ...
form1.html(片段)
<html>
<body>
{{ legal_text }} <!-- this is NOT displayed properly when errors occur -->
<h4><strong>{{ form.q1.label }}</strong></h4>
{% if form.q1.errors %}
<div class="alert alert-danger" role="alert">{{form.q1.errors }}</div>
{% endif %}
{{ form.q1.help_text }}
{{ form.q1 }}
<h4><strong>{{ form.q2.label }}</strong></h4>
{% if form.q2.errors %}
<div class="alert alert-danger" role="alert">{{form.q2.errors }}</div>
{% endif %}
{{ form.q2.help_text }}
{{ form.q2 }}
</body>
</html>
1 回答
在这里,您将覆盖表单clean方法而不返回clean_data . 替换你的代码