0

我有 2 个字段 - fieldA、fieldB - 我想阻止用户提交表单。

class IntroductionForm(ModelForm):
    class Meta:
         ...
def clean_fieldA(self):
    fieldA = self.cleaned_data.get('fieldA', True)
    fieldB = self.cleaned_data.get('fieldB', True)
    if not self.instance.fieldB == fieldB and not self.instance.fieldA == fieldA:
            raise ValidationError("You may not choose both fields")

    return fieldA

目前,如果没有验证错误,我根本无法选择 fieldA。那么应该怎么做呢?

谢谢!

4

4 回答 4

3

查看文档中关于清理和验证相互依赖的字段的说明。正确的做法是覆盖该clean()方法,该方法在调用各个clean_FIELD()方法后被调用。

class IntroductionForm(ModelForm):
    ....
    def clean(self):
        cleaned_data = super(IntroductionForm, self).clean()
        fieldA = bool(self.cleaned_data.get('fieldA'))
        fieldB = bool(self.cleaned_data.get('fieldB'))

        if fieldA and fieldB:
            raise forms.ValidationError("Can't select both forms")
        return cleaned_data

用户是否必须选中其中一个框并不完全清楚。然后,您必须将条件更改fieldA and fieldBfieldA != fieldB。在这种情况下,您还可以考虑使用单选框。

于 2013-06-27T07:35:22.310 回答
1

所以这是正确的解决方案(对我有用)。因为我需要同时验证两个字段,所以我使用 clean(self) 而不是特定的 clean_fieldA(self) - 这种方式。

def clean(self):
    cleaned_data = super(IntroductionForm, self).clean()
    fieldA = cleaned_data.get('fieldA')
    fieldB = cleaned_data.get('fieldB')
    if fieldA and fieldB:
        raise ValidationError("You may not choose both fields!")

    return cleaned_data
于 2013-06-27T07:33:27.150 回答
0
class IntroductionForm(ModelForm):
    class Meta:
         ...
def clean_fieldA(self):
    fieldA = self.cleaned_data['fieldA']
    fieldB = self.cleaned_data['fieldB']
    if self.instance.fieldB == fieldB and  self.instance.fieldB == fieldA:
            raise ValidationError("You may not choose both fields")

    return fieldA
于 2013-06-27T07:22:44.577 回答
0

您首先检查干净数据中的字段并检查那里的值。

def clean_fieldA(self):

    if 'fieldA' in self.cleaned_data and 'fieldB' in self.cleaned_data:
        if self.cleaned_data['fieldA'] != self.cleaned_data['fieldB']:
            raise forms.ValidationError(_("You may not choose both fields."))

    return self.cleaned_data['fieldA']

希望对你有帮助 :)

于 2013-06-27T07:25:25.840 回答