1

表格.py

class PhoneinfoForm(forms.ModelForm):

    pname = forms.CharField(required=True)
    pnumber = forms.IntegerField(required=True)
    gname = forms.CharField(required=False)
    gnumber = forms.IntegerField(required=False)
    class Meta:
        model = Phone_info
        fields = ['pname','pnumber','gname','gnumber']

    def clean(self):
        cleaned_data = self.cleaned_data
        pname = cleaned_data.get("pname")
        pnumber = cleaned_data.get("pnumber")
        gname = cleaned_data.get("gname")
        gnumber = cleaned_data.get("gnumber")

        if 'pname' and 'pnumber' not in cleaned_data: 
            raise forms.ValidationError
        if 'gname' and 'gnumber' not in cleaned_data: 
            raise forms.ValidationError

        return cleaned_data

我正在尝试验证姓名和号码。就我而言,pname并且pnumber是一组必填字段,我实现了我的付出required=True

第二件事是gname并且gnumber不是强制性的,但是如果gnumber输入,那么它gname不应该发生(如果在 gname 中没有输入任何内容,则它正在接受)。如果输入数字,它不应该接受没有名称,反之亦然。

我的代码不适用于第二选择,如何验证这一点。

谢谢

4

1 回答 1

1

您的代码中有几个不好的地方:

1)使用forms.ModelForm时不需要在表单中声明字段,如果对应的模型字段有相同的约束。从问题示例中,如果模型中Phone_info对应的字段具有与blank表单相同的属性required,则不需要在模型表单中再次声明字段。

2)根据要求pnamepnumber您无需手动检查它们是否已填充。已经由ModelForm. 所以这很奇怪,必须删除:

if 'pname' and 'pnumber' not in cleaned_data: 
    raise forms.ValidationError

3)这条线不会做预期的事情:

if 'gname' and 'gnumber' not in cleaned_data

它将首先检查条件'gnumber' not in cleaned_data。结果将是布尔值(真/假)。然后if 'gname' and False/True将应用条件。

你想要的是:

gname = self.cleaned_data.get("gname", None)
gnumber = self.cleaned_data.get("gnumber", None)
if gname and gnumber is None:
    raise forms.ValidationError("gnumber must be filled")
if gnumber is not None and not gname:
    raise forms.ValidationError("gname must be filled")

4)正如您在第 3 页中提到的,forms.ValidationError必须在引发时初始化:

raise forms.ValidationError("Error message")

所以结果代码

class PhoneinfoForm(forms.ModelForm):

    # delete these fields, if they are the same, as in Phone_info
    pname = forms.CharField(required=True)
    pnumber = forms.IntegerField(required=True)
    gname = forms.CharField(required=False)
    gnumber = forms.IntegerField(required=False)

    class Meta:
        model = Phone_info
        fields = ['pname', 'pnumber', 'gname', 'gnumber']

    def clean(self):
        gname = self.cleaned_data.get("gname", None)
        gnumber = self.cleaned_data.get("gnumber", None)
        if gname and gnumber is None:
            raise forms.ValidationError("gnumber must be filled")
        if gnumber is not None and not gname:
            raise forms.ValidationError("gname must be filled")

        return self.cleaned_data
于 2013-05-16T07:30:56.663 回答