Django:表单模型验证

时间:2018-04-19 08:09:47

标签: django django-forms

我对表单模型验证有一个理解问题。我有一个模型和其他我在我的表单中添加了email_confirm字段。但是,验证不起作用。谁能帮助我理解为什么?

class TransactionProfileModelForm(forms.ModelForm):
    email_confirm = forms.EmailField()

    class Meta:
        model=TransactionProfile
        fields = [
            'email',
            'email_confirm',
            'address_line_1',
            'address_line_2',
            'city',
            'country',
            'postal_code',
            'state'
        ]

    def clean_email(self):
        email = self.cleaned_data.get('email')
        email_confirm = self.cleaned_data.get('email_confirm')
        if email and email_confirm and email != email_confirm:
            raise forms.ValidationError("Emails don't match.")
        return email

但是,如果我在这里尝试此代码,它可以工作:

    def clean_email_confirm(self):
        email = self.cleaned_data.get('email')
        email_confirm = self.cleaned_data.get('email_confirm')
        if email and email_confirm and email != email_confirm:
            raise forms.ValidationError("Emails don't match.")
        return email_confirm

1 个答案:

答案 0 :(得分:2)

调用点clean_email()时不存在

clean_email_confirm(),因为尚未清除确认字段字段。

字段按字母顺序清理,因此在clean()中进行比较有效。然而,这是一个实施细节,不应该依赖;正如文档所述,任何依赖于两个或多个字段的验证都应该在通用 WebElement elem = new WebDriverWait(driver, 1).until(ExpectedConditions.visibilityOfElementLocated(By.xpath(HAMBURGER_MENU_GENERAL_XPATH))); 方法中完成,而不是任何特定于字段的方法。