Wednesday, September 26, 2012

Re: Using email instead of username for registration and login

I opted to customize a little.

First the backend:

from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User


class EmailBackend(ModelBackend):
"""A django.contrib.auth backend that authenticates the user based on its
email address instead of the username.
"""

def authenticate(self, email=None, password=None):
"""Authenticate user using its email address instead of username."""
try:
user = User.objects.get(email=email)
if user.check_password(password):
return user
except User.DoesNotExist:
return None

Then setup settings accordingly (notice that I wrote the backend inside an app called 'accounts'):

AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend', # necessary for django.auth
'accounts.backends.EmailBackend' # custom backend to authenticate using the email field
)

And then modify your login view:

if request.method == 'POST' and username and password:
user = auth.authenticate(username=username, password=password)
if user is None:
user = auth.authenticate(email=email, password=password)

What do you think? I know it is not that simple but I couldn't figure out an easier/cleaner way to do it.

On Monday, September 24, 2012 10:57:20 PM UTC-3, Bill Beal wrote:
Hi all,

I want to use the email address as the username for registration and login.  I'm using django-registration for 2-stage registration.  I'm looking for an easier way than what I've come up with so far.  I can modify registration and activation, but then django.contrib.auth.views.login has a 30-character limit on the username.  I'm not looking forward to making username act like an email address.  Any quick fixes?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/S6IA5wIf6FQJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment