我希望根据将布尔值设置为True或False来有条件地需要一个字段。
如果is_company设置为True,我应该返回set required = 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
答案 0 :(得分:31)
查看文档中的Cleaning and validating fields that depend on each other章节。
文档中给出的示例可以很容易地适应您的场景:
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