开发者

Making an exception in EmailField validation in django

I have model called EmailHistory with one of the fields that look like this:

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

I created a ModelForm and want to validate for email addresses unless it's set to "Anonymous". I tried the following, to no avail.

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

    to_emails = forms.CharField()

    def clean_from_email(self):

       开发者_如何学Go from_email = self.cleaned_data['from_email']
        if from_email == "Anonymous":
            return from_email
        else:
            return super(EmailForm, self).clean_from_email();


I suspect the issue is that, as the documentation explains, the clean method of the underlying form field - which in turn runs the validators - is run before the specific clean_form_field method in the form itself. You'll probably want to use a normal CharField in your form, and add the email validation into the clean method yourself.


I couldn't get it to work without redefining from_email. So, I redefined it and then did an email validation using 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜