djagno重写authenticate实现帐号和邮箱的多方式登录。

1、在users应用的view中重写authenticate:

from django.contrib.auth.backends import ModelBackend
from django.db.models import Q

from .models import UserProfile


class CustomBackend(ModelBackend):
    def authenticate(self, username=None, password=None, **kwargs):
        try:
            user =UserProfile.objects.get(Q(username=username)|Q(email=username))
            if user.check_password(password):
                return  user
        except Exception as e:
            return None

2、在settings中进行声明:

AUTHENTICATION_BACKENDS = (
    'users.views.CustomBackend',
)
 
原文地址:https://www.cnblogs.com/draculaqk/p/7502057.html