Log in user using either email address or username in Django

后端 未结 13 2616
故里飘歌
故里飘歌 2020-12-02 08:34

I am trying to create an auth backend to allow my users to log in using either their email address or their username in Django 1.6 with a custom user model. The backend work

13条回答
  •  忘掉有多难
    2020-12-02 08:54

    After following the advice given to me above and changing AUTHENTICATION_BACKENDS = ['yourapp.yourfile.EmailOrUsernameModelBackend'] I was getting the error Manager isn't available; User has been swapped for 'users.User'. This was caused because I was using the default User model instead of my own custom one. Here is the working code.

    from django.conf import settings
    from django.contrib.auth import get_user_model
    
    class EmailOrUsernameModelBackend(object):
        """
        This is a ModelBacked that allows authentication with either a username or an email address.
    
        """
        def authenticate(self, username=None, password=None):
            if '@' in username:
                kwargs = {'email': username}
            else:
                kwargs = {'username': username}
            try:
                user = get_user_model().objects.get(**kwargs)
                if user.check_password(password):
                    return user
            except User.DoesNotExist:
                return None
    
        def get_user(self, username):
            try:
                return get_user_model().objects.get(pk=username)
            except get_user_model().DoesNotExist:
                return None
    

提交回复
热议问题