0

EmailHistory使用如下所示的字段之一调用模型:

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

我创建了一个 ModelForm 并希望验证电子邮件地址,除非它设置为“匿名”。我尝试了以下方法,但无济于事。

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();
4

2 回答 2

0

我怀疑问题在于,正如文档所解释的那样,clean底层表单字段的方法(依次运行验证器)clean_form_field在表单本身的特定方法之前运行。您可能希望在表单中使用普通的 CharField,并自己将电子邮件验证添加到 clean 方法中。

于 2011-02-13T11:07:39.560 回答
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
于 2011-02-14T20:04:47.927 回答