我有一个表单,其中没有任何字段是单独需要的,但如果所有字段都留空,我想提出验证错误。做这个的最好方式是什么?我尝试了以下但它没有工作:
def clean(self):
cleaned_data = super(SearchForm, self).clean()
if len(cleaned_data) == 0:
raise forms.ValidationError(ugettext_lazy("You must fill at least one field!"))
答案 0 :(得分:3)
不是检查cleaned_data
的长度(它应该始终包含每个表单字段的一个条目),而应检查每个条目并确认值都是空的。
这是一个如何做到这一点的例子。
def clean(self):
cleaned_data = super(SearchForm, self).clean()
form_empty = True
for field_value in cleaned_data.itervalues():
# Check for None or '', so IntegerFields with 0 or similar things don't seem empty.
if field_value is not None and field_value != '':
form_empty = False
break
if form_empty:
raise forms.ValidationError(ugettext_lazy("You must fill at least one field!"))
return cleaned_data # Important that clean should return cleaned_data!
答案 1 :(得分:0)
忽略仅填充空格的字段:and not field_value.isspace()