0

我有一个表单,其中不需要单独的任何字段,但是如果所有字段都留空,我想引发验证错误。做这个的最好方式是什么?我尝试了以下方法,但没有奏效:

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!"))
4

2 回答 2

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!
于 2012-04-21T21:05:31.797 回答
0

忽略仅填充空格的字段:and not field_value.isspace()

于 2015-12-07T19:16:38.350 回答