在django中的EmailField验证中例外

时间:2011-02-13 08:18:48

标签: django validation django-forms emailfield

我有一个名为EmailHistory的模型,其中一个字段如下所示:

from_email = models.EmailField(verbose_name="From:")

我创建了一个ModelForm,并希望验证电子邮件地址,除非它设置为“Anonymous”。我试过以下,但没有用。

class EmailForm(ModelForm):
    class Meta:
        model = EmailHistory
        exclude = ('to_email')

    to_emails = forms.CharField()

    def clean_from_email(self):

        from_email = self.cleaned_data['from_email']
        if from_email == "Anonymous":
            return from_email
        else:
            return super(EmailForm, self).clean_from_email();

2 个答案:

答案 0 :(得分:0)

我怀疑问题是,正如the documentation所解释的那样,基础表单字段的clean方法 - 它反过来运行验证程序 - 在特定的clean_form_field方法之前运行形式本身。您可能希望在表单中使用普通的CharField,并自行将电子邮件验证添加到clean方法中。

答案 1 :(得分:0)

如果不重新定义from_email,我就无法工作。所以,我重新定义了它,然后使用django.core.validators.validate_email进行了电子邮件验证:

class EmailForm(ModelForm):
    class Meta:
        model = EmailHistory
        exclude = ('to_email')

    to_emails = forms.CharField()
    from_email = forms.CharField(required=True)

    def clean_from_email(self):
        from_email = self.cleaned_data['from_email']
        if from_email == "Anonymous":
            from_email = "myemail@example.com"

        validate_email(from_email)

        return from_email