简体   繁体   中英

Allowing multiple options in username field in django login

I am working on a django website. I have a custom user model as follows:

class MyUser(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    mobile = models.CharField(max_length=12)
    first_name=models.CharField(max_length=20)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    objects = MyUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['mobile','first_name']

I am wanting to also add mobile to the username field so that a user can login using both email and mobile . I looked up to django docs but wasnt able to figure out a solution that would have worked for me. Please tell me a way so that I can proceed with it.

Login view:

def login(request):

    if request.user.is_authenticated:
        return redirect('/')
    else:
        if request.method == "POST":
            email=request.POST['email']
            password=request.POST['password']
            user=auth.authenticate(email=email,password=password)

            if user is not None:
                auth.login(request, user)
                return redirect('/')
            else:
                messages.info(request,"Email Password didn't match")
                return redirect('login')
        else:
            return render(request,"login.html")

I have customized an example from Django's docs:

from django.db.models import Q
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import BaseBackend
from django.contrib.auth.hashers import check_password
from django.contrib.auth.models import User

class CustomAuthenticationBackend(BaseBackend):
    def authenticate(self, request, login_field=None, password=None):
        try:
            user = get_user_model().objects.get(
                Q(email=login_field) | Q(phone=login_field)
            )
        except User.DoesNotExist:
            return
        if user.check_password(password):            
            return user

    def get_user(self, user_id):
        try:
            return get_user_model().objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

Don't forget to insert your CustomAuthenticationBackend into AUTHENTICATION_BACKENDS at your settings. See detailed here: https://docs.djangoproject.com/en/3.1/topics/auth/customizing/#writing-an-authentication-backend

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM