我有一个'start=forms.DateInput'
,end=forms.DateInput
和active=forms.CheckboxInput
的表单,但是当我试图验证这些字段时,我有这些错误。
KeyError at /employee/edit/70000007/
'end'
…
if form.is_valid():
…
end = self.cleaned_data['end']
但是当只应用一个验证器时,这很好。
def clean_end(self):
start = self.cleaned_data['start']
end = self.cleaned_data['end']
if end < start:
raise forms.ValidationError('end date cannot be less than start date.')
return end
def clean_active(self):
active = self.cleaned_data['active']
end = self.cleaned_data['end']
if active and end:
raise forms.ValidationError('active employee should cannot be end date')
return active
谢谢你的帮助。
使用clean方法可以正常工作。
# forms.py
def clean(self):
cleaned_data = super().clean()
start = cleaned_data.get('start')
end = cleaned_data.get('end')
active = cleaned_data.get('active')
if end < start:
raise forms.ValidationError('end date cannot be less than start date.')
if end and active:
raise forms.ValidationError('active employee should cannot be end date.')
# template.html
{% for error in form.non_field_errors %}
{{error}}
{% endfor %}