Skip to content

Instantly share code, notes, and snippets.

@mgrouchy
Created April 1, 2011 00:34
Show Gist options
  • Save mgrouchy/897544 to your computer and use it in GitHub Desktop.
Save mgrouchy/897544 to your computer and use it in GitHub Desktop.
#in your forms
#if you are using django.contrib.auth.views.login
#pass EmailAuthenticationForm to the authentication_form argument.
class EmailAuthenticationForm(AuthenticationForm):
"""
Extends the standard django AuthenticationForm, to support 75 character
usernames. 75 character usernames are needed to support the EmailOrUsername
auth backend.
"""
required_css_class = 'required'
username = forms.CharField(label=_('Username'), max_length=75)
password = forms.CharField(label=_('Password'), widget=forms.PasswordInput)
def __init__(self, request=None, *args, **kwargs):
self.request = request
self.user_cache = None
super(AuthenticationForm, self).__init__(*args, **kwargs)
from django.core.validators import email_re
class EmailOrUsernameModelBackend(ModelBackend):
"""Allows a user to login using their email address, and not just their
username.
"""
def _lookup_user(self, username):
try:
if email_re.search(username):
user = User.objects.get(email=username.lower())
else:
user = User.objects.get(username=username)
except User.DoesNotExist:
return None
return user
def authenticate(self, username=None, password=None):
user = self._lookup_user(username)
if user:
if user.check_password(password):
return user
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment