class FooForm(forms.ModelForm):
foo_date = forms.CharField(required=True)
foo_time = forms.CharField(required=True)
我怎样才能实现这样的目标:
如果填写foo_data
,则foo_time
应为required=False
,反之亦然。有可能吗?
答案 0 :(得分:4)
为这两个字段设置required=False
,然后检查至少填写了一个字段的clean
方法。
class FooForm(forms.ModelForm):
foo_date = forms.CharField(required=False)
foo_time = forms.CharField(required=False)
def clean(self):
cleaned_data = super(FooForm, self).clean()
if not (cleaned_data.get('foo_date') or cleaned_data.get('foo_time')):
raise forms.ValidationError('Either foo_date or foo_time is required')
return cleaned_data