0

I'm using the UserModel and the UserCreationForm in Django. However, instead of requiring a username, I want to use the customer's email as the login information (i.e. completely bypass / ignore the username field).

  1. How do I go about making the username field to be optional in the User Model
  2. How do I turn email into the customer's "username"? In turn, how do I make this email field to be required then?
goelv
  • 2,774
  • 11
  • 32
  • 40
  • possible duplicate of [Accepting email address as username in Django](http://stackoverflow.com/questions/778382/accepting-email-address-as-username-in-django) – Paulo Scardine Aug 13 '12 at 17:19

1 Answers1

1

1.) Just make the username field optional in your form and to the model pass the email as the username, after stripping out '@' from the email.

2) Create a custom authentication backend (this will accept either the username or email):

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

chage your settings accordingly :

AUTHENTICATION_BACKENDS = (
    'myoursite.backends.EmailOrUsernameBackend', # Custom Authentication to accept usernamee or email
)
Arsh Singh
  • 2,038
  • 15
  • 16
  • Cool, thanks! I just got another idea from your post though. Instead of entering the username, how do I get it so that everything in the email before the @ sign (ex: goelv from goelv@gmail.com) becomes the username? Is that something I would handle in the view? I'm new at this, thanks for the help! – goelv Aug 13 '12 at 17:29
  • Well, that's not very realistic.... what if two users have email addresses masteryoda@gmail.com and masteryoda@yahoo.com, they can't have the same username – Arsh Singh Aug 13 '12 at 17:33
  • i'm working on a system where the first part would be unique so it could be viable – goelv Aug 13 '12 at 17:37
  • 1
    If you really want to do it, you can just not display the username field in your template and edit your view to pass the username to the form like this: http://snippi.com/s/f1vipav – Arsh Singh Aug 13 '12 at 17:46