在django表格

时间:2018-06-01 12:25:34

标签: django python-2.7

我有像这样的表单字段

所以

如何只将一个字段设为强制或再见。在提交表单django

时,至少需要一个字段为强制字段,另一个字段可选
 class MeForm(forms.Form):
        hi = forms.CharField(max_length=100)
        by = forms.CharField(max_length=100)

1 个答案:

答案 0 :(得分:1)

您可以为此覆盖clean方法:

class MeForm(forms.Form):
    hi = forms.CharField(max_length=100, required=False)
    by = forms.CharField(max_length=100, required=False)

    def clean(self):
        hi = self.cleaned_data.get('hi')
        by = self.cleaned_data.get('by')
        if not hi and not by:
            raise forms.ValidationError('One of fields is required')
        return self.cleaned_data