Question

How don't call clean_ method in 'required=False' field?

forms.py

from django import forms

class userRegistrationForm(forms.Form):
    username = forms.CharField(
        max_length=30,
    )
    password1 = forms.CharField(
        widget=forms.PasswordInput(),
    )

    email = forms.EmailField(  # If user fill this, django will call 'clean_email' method.
        required=False,  # But when user don't fill this, I don't want calling 'clean_email' method.
    )

    def clean_email(self):
        if 'email' in self.cleaned_data:
            try:
                User.objects.get(email=self.cleaned_data['email'])
            except ObjectDoesNotExist:
                return self.cleaned_data['email']
            else:
                raise forms.ValidationError('Wrong Email!')

User can fill 'email' and don't need to fill 'email' field.

What should I do?

Was it helpful?

Solution

If you have a clean_field, it will be called irrespective of whether you fill it or not because this is internally called by django's full_clean.

Seems you only want to do your custom validation if some email was provided. So, you can do:

def clean_email(self):
    email = self.cleaned_data['email']
    #If email was provided then only do validation
    if email:
        try:
            User.objects.get(email=self.cleaned_data['email'])
        except ObjectDoesNotExist:
            return email
        else:
            raise forms.ValidationError('Wrong Email!')
    return email
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top