22

我想要一个基于将布尔值设置为Trueor有条件地需要的字段False

required =True如果is_company设置为,我应该返回什么设置True

class SignupFormExtra(SignupForm):
    is_company = fields.BooleanField(label=(u"Is company?"), 
                                     required=False)
    NIP = forms.PLNIPField(label=(u'NIP'), required=False)

    def clean(self):
        if self.cleaned_data.get('is_company', True):
            return ...?
        else:
            pass
4

1 回答 1

38

检查文档中有关清理和验证相互依赖的字段的章节。

文档中给出的示例可以很容易地适应您的场景:

def clean(self):
    cleaned_data = super(SignupFormExtra, self).clean()
    is_company = cleaned_data.get("is_company")
    nip = cleaned_data.get("NIP")
    if is_company and not nip:
        raise forms.ValidationError("NIP is a required field.")
    return cleaned_data
于 2012-06-10T10:19:41.723 回答