Log in user using either email address or username in Django

后端 未结 13 2613
故里飘歌
故里飘歌 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 09:17

    I know this is already answered, however I have found a real neat way to implement login with both e-mail and username using the Django auth views. I did not see anyone use this type of method so I thought I'd share it for simplicity's sake.

    from django.contrib.auth.models import User
    
    
    class EmailAuthBackend():
        def authenticate(self, username=None, password=None):
            try:
                user = User.objects.get(email=username)
                if user.check_password(raw_password=password):
                    return user
                return None
            except User.DoesNotExist:
                return None
    
        def get_user(self, user_id):
            try:
                return User.objects.get(pk=user_id)
            except User.DoesNotExist:
                return None
    

    Then in your settings.py add this

    AUTHENTICATION_BACKENDS = (
        'django.contrib.auth.backends.ModelBackend',
        'myapp.authentication.EmailAuthBackend',
    )
    

提交回复
热议问题