Custom login in Django

Posted by alpgs on Stack Overflow See other posts from Stack Overflow or by alpgs
Published on 2010-05-30T16:15:52Z Indexed on 2010/05/30 16:22 UTC
Read the original article Hit count: 287

Filed under:
|
|

Django newbie here.

I wrote simplified login form which takes email and password. It works great if both email and password are supplied, but if either is missing i get KeyError exception. According to django documentation this should never happen:

By default, each Field class assumes the value is required, so if you pass an empty value -- either None or the empty string ("") -- then clean() will raise a ValidationError exception

I tried to write my own validators for fields (clean_email and clean_password), but it doesn't work (ie I get KeyError exception). What am I doing wrong?

class LoginForm(forms.Form):
    email = forms.EmailField(label=_(u'Your email'))
    password = forms.CharField(widget=forms.PasswordInput, label=_(u'Password'))

    def clean_email(self):
        data = self.cleaned_data['email']
        if not data:
            raise forms.ValidationError(_("Please enter email"))
        return data

    def clean_password(self):
        data = self.cleaned_data['password']
        if not data:
            raise forms.ValidationError(_("Please enter your password"))
        return data

    def clean(self):
        try:
            username = User.objects.get(email__iexact=self.cleaned_data['email']).username
        except User.DoesNotExist:
            raise forms.ValidationError(_("No such email registered"))
        password = self.cleaned_data['password']

        self.user = auth.authenticate(username=username, password=password)
        if self.user is None or not self.user.is_active:
            raise forms.ValidationError(_("Email or password is incorrect"))
        return self.cleaned_data

© Stack Overflow or respective owner

Related posts about django

Related posts about validation