Search code examples
pythondjangodjango-modelsdjango-formsdjango-users

How to make customer's email as the username in UserCreationForm / User Model in Django?


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?

Solution

  • 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
    )