Search code examples
pythondjangodjango-formsdjango-validation

how to check confirm email the same in django


I have the following form:

class SignupForm(forms.ModelForm):
    time_zone = forms.ChoiceField(choices=TIMEZONE_CHOICES) 
    email = forms.EmailField()
    confirm_email = forms.EmailField()
    password1 = forms.CharField(widget=forms.PasswordInput())
    password2 = forms.CharField(widget=forms.PasswordInput())     

    class Meta:
        model = Customer
        fields = (
                  'first_name', 
                  'last_name',
                  'coupon_code'
                  )

    def clean_email(self):
        email = self.cleaned_data['email']
        print 'email cleaned data: '+cleaned_data
        try:
            User.objects.get(email=email)
            raise forms.ValidationError('Email already exists.')
        except User.DoesNotExist:
            return email

    def clean_confirm_email(self):
        print '-----'
        print 'confirm email cleaned data: '+cleaned_data
        email = self.cleaned_data['email']
        confirm_email = self.cleaned_data['confirm_email']
        if email != confirm_email:
            raise forms.ValidationError('Emails do not match.')
        return confirm_email

This prints:

email cleaned data: 
{'coupon_code': u'coup', 'first_name': u'Gina', 'last_name': u'Silv', 'time_zone': u'America/New_York', 'email': u'[email protected]'}
-----
confirm email cleaned data: 
{'first_name': u'Gina', 'last_name': u'Silv', 'confirm_email': u'[email protected]', 'time_zone': u'America/New_York', 'coupon_code': u'coup'}

When this runs I get the error:

key error 'email' self.cleaned_data['email']

How can I access the email field in the clean_confirm_email method?


Solution

  • You shouldn't perform that validation in the clean_confirm_email() method. Instead, do it in the clean() method as recommended, like so:

    def clean(self):
            cleaned_data = super(SignupForm, self).clean()
            email = cleaned_data.get("email")
            confirm_email = cleaned_data.get("confirm_email")
    
            if email and confirm_email:
            # Only do something if both fields are valid so far.
                if email != confirm_email:
                    raise forms.ValidationError("Emails do not match.")
    
            return cleaned_data
    

    More info here: https://docs.djangoproject.com/en/1.6/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other