i want a example. thanks
views:
123answers:
1
+2
A:
You can't easily store emails in django.contrib.auth.model.User's username field, so you'll need a different auth backend. Put the following somewhere and add its path to AUTHENTICATION_BACKENDS. See http://docs.djangoproject.com/en/dev/topics/auth/#writing-an-authentication-backend
from django.contrib.auth.models import User
class EmailBackend(object):
""" Authenticates against the email field of django.contrib.auth.models.User
"""
def authenticate(self, email=None, password=None):
# Try using the email if it is given
if email:
for user in User.objects.filter(email=email):
if user.check_password(password):
return user
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
Then, in your views, authenticate by calling django.contrib.auth.authenticate.
Two things to note:
- You will probably want to keep the default
AUTHENTICATION_BACKENDthere, especially if you want to use the Django admin. - If users are signing themselves up without a username, you'll need to create one for them. I use the base64 version of a uuid for that
Set the username in a save method somewhere (eg in your new user form):
import uuid, binascii
username = binascii.b2a_base64(uuid.uuid4().bytes)
Will Hardy
2010-01-24 03:27:47
+1 for 'You can't easily store emails'. The User.username field a) is only 30 chars long and that's not long enough for some emails, and b) it requires the name to match '\w+', which does not allow things like '@' or '.'. This does create the problem of what to *use* for the username (since it's required) if you only want to focus on email addrs. I recommend slugifying the email (e.g. [email protected] => foo_bar_com), trim to 30 chars and storing that (but be prepared to handle accidental collisions). The user will never see it, and your authentication backend will completely ignore it.
Peter Rowell
2010-01-24 18:20:53
in 1.2 you can use emails for login
alex
2010-03-31 04:00:36
more on that: 1.2 now allows chars that are in emails to be used in usernames (see http://code.djangoproject.com/changeset/12634). As the commit message admits, it's not a complete solution as the max length is still only 30 chars.
Will Hardy
2010-04-01 05:35:52