Authenticate user using email and password

后端 未结 3 1903
我寻月下人不归
我寻月下人不归 2021-02-09 23:36

I have a form that only allow users to login via username . I decided to only allow user to login via email instead of username.

First, this is not a duplication of any

3条回答
  •  臣服心动
    2021-02-10 00:07

    You can also write a custom backend:

    # yourapp.backends.py    
    from django.contrib.auth.models import User
    
    
    class EmailOrUsernameModelBackend(object):
        """ Authenticate user by username or email """
        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
                else:
                    return None
            except User.DoesNotExist:
                return None
    
        def get_user(self, user_id=None):
            try:
                return User.objects.get(pk=user_id)
            except User.DoesNotExist:
                return None
    

    Now add your backend to settings.py:

    AUTHENTICATION_BACKENDS = (
        'yourapp.backends.EmailOrUsernameModelBackend',
        'django.contrib.auth.backends.ModelBackend',
    )
    

提交回复
热议问题