Allow users to login with email address in addition to username.

master
Nick Sergeant 2013-05-13 10:03:27 -04:00
parent e01873fe39
commit 1871ec8ef6
5 changed files with 29 additions and 5 deletions

View File

@ -133,6 +133,10 @@ MIDDLEWARE_CLASSES = (
'blogs.middleware.BlogMiddleware',
)
AUTHENTICATION_BACKENDS = (
'utils.backends.EmailOrUsernameModelBackend',
)
ROOT_URLCONF = 'snipt.urls'
PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))

View File

@ -28,7 +28,7 @@
<fieldset>
<legend>Log in</legend>
<div class="control-group {% if form.username.errors %}error{% endif %}">
<label class="control-label" for="id_username">Username</label>
<label class="control-label" for="id_username">Username or email:</label>
<div class="controls">
{{ form.username }}
{% if form.errors.username %}

View File

@ -60,8 +60,7 @@ urlpatterns = patterns('',
url(r'^search/$', search),
url(r'^register/$', lambda x: HttpResponseRedirect('/signup/')),
url(r'^signup/$',
SniptRegistrationView.as_view(),
url(r'^signup/$', SniptRegistrationView.as_view(),
name='registration_register'),
url(r'', include('registration.backends.default.urls')),
@ -69,4 +68,5 @@ urlpatterns = patterns('',
)
if settings.DEBUG:
urlpatterns = urlpatterns + static('/media/', document_root=os.path.join(settings.BASE_PATH, 'media'))
urlpatterns = urlpatterns + static('/media/',
document_root=os.path.join(settings.BASE_PATH, 'media'))

21
utils/backends.py Normal file
View File

@ -0,0 +1,21 @@
from django.conf import settings
from django.contrib.auth.models import User
class EmailOrUsernameModelBackend(object):
def authenticate(self, username=None, password=None):
if '@' in username:
kwargs = {'email': username}
else:
kwargs = {'username': username}
try:
user = User.objects.get(**kwargs)
if user.check_password(password):
return user
except User.DoesNotExist:
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None

View File

@ -3,7 +3,6 @@ from registration.forms import RegistrationForm
from django.contrib.auth.models import User
from django import forms
class SniptRegistrationForm(RegistrationForm):
"""
Subclass of ``RegistrationForm`` which enforces uniqueness of