Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Django Forms Forms Clean Two Fields

ospel
ospel
9,523 Points

Checking field equality in Django Forms

What could possibly be wrong in my code?

myproject/forms.py
from django import forms


def not_treehouse(value):
    if value.lower().endswith('@teamtreehouse.com'):
        raise forms.ValidationError('Just come talk to me')


class LeadShareForm(forms.Form):
    email = forms.EmailField(validators=[not_treehouse])
    email2 = forms.EmailField(label='Email again', validators=[not_treehouse])
    link = forms.URLField()
    honeypot = forms.CharField(widget=forms.HiddenInput, required=False)

    def clean_honeypot(self):
        honey = self.cleaned_data['honeypot']
        if len(honey):
            raise forms.ValidationError('Bad robot!')
        return honey

    def clean(self):
        cleaned_data = super().clean()
        email = cleaned_data.get('email1')
        verify = cleaned_data.get('email2')

        if email != verify:
            raise forms.ValidationError("The email addresses need to be the same!")

1 Answer

Hasan Ahmad
Hasan Ahmad
6,727 Points

For me, changing cleaned_data.get('email') to cleaned_data['email'] helped me solve the problem. This is what i did to fix your problem:

     def clean(self):
        cleaned_data = super().clean()
        email = cleaned_data['email']
        email2 = cleaned_data['email2']

        if email != email2:
            raise forms.ValidationError("The email addresses need to be the same!")
ospel
ospel
9,523 Points

That was the problem, thx a lot!