同时验证两个字段

时间:2015-07-30 15:12:05

标签: django django-models

我正在查看这篇文档:

https://docs.djangoproject.com/en/1.8/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other

该文档解释了如何完成字段依赖,但我的问题略有不同:

假设我有一个包含两个字段的模型:

class MyModel(models.Model):
    field1 = models.CharField(max_length=200)
    field2 = models.CharField(max_length=200)

并且说两个字段中的一个是隐藏的,因此模型形状如下:

class MyModelForm(forms.ModelForm):
    class Meta:
        ...

        widgets = {'field2': forms.HiddenImput()}

现在,当用户填写表单时,我(在clean_field1上)也会填写field2。现在,我想将field2发生的任何错误报告为field1错误。这是因为此刻,用户不知道他做错了什么!

我尝试做的是,在ModelForm定义中:

def clean(self):
    cleaned_data = super(MyModelForm, self).clean()
    # Do something here
    return cleaned_data

这是Django页面上显示的内容。但问题是,当clean方法执行时,字典self.errors为空,所以我不知道该怎么做......

1 个答案:

答案 0 :(得分:2)

我不确定我的答案。但是,我们假设您使用field1数据来生成field2值。您可以使用自定义方法生成它,并将其分配给__init__方法中的字段。这将为您提供一个以后清理这两个字段的好方法。

class MyModelForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)

        # now lets generate field2 data using field1 data.. 
        self.data['field2'] = self.field[1] * 154220

    class Meta:
        widgets = {'field2': forms.HiddenInput()}    


    def clean_field1(self):
        ## Here you can do validation for field1 only.
        ## Do it like field2 is not exisited. 


    def clean_field2(self):
        ## Here you can do validation for field2 only.
        ## Do it like field1 is not exisited. 

    def clean(self):
        """
        In here you can validate the two fields
        raise ValidationError if you see anything goes wrong. 
        for example if you want to make sure that field1 != field2
        """
        field1 = self.cleaned_data['field1']
        field2 = self.cleaned_data['field2']

        if field1 == field2:
            raise ValidationError("The error message that will not tell the user that field2 is wrong.")

        return self.cleaned_data

<强>更新

如果您希望clean方法在特定字段中引发错误:

  

请注意,Form.clean()覆盖引发的任何错误都不会   特别是与任何领域相关联。他们进入一个特殊的   “field”(称为 all ),您可以通过该访问权限访问   如果需要,可以使用non_field_errors()方法。如果要附加错误   到表单中的特定字段,您需要调用add_error()。

因此,从Django文档中,您可以使用add_error()来完成您想要实现的目标。

代码可以这样

def clean(self):
    """
    In here you can validate the two fields
    raise ValidationError if you see anything goes wrong. 
    for example if you want to make sure that field1 != field2
    """
    field1 = self.cleaned_data['field1']
    field2 = self.cleaned_data['field2']

    if field1 == field2:
        # This will raise the error in field1 errors. not across all the form
        self.add_error("field1", "Your Error Message")

    return self.cleaned_data

请注意,上述方法是Django 1.7及更高版本的新方法。

https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.add_error