Search code examples
djangovalidationdjango-formsemailfield

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):

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

Solution

  • 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.