首页 > 技术文章 > 重写authenticate, 让mobil也能作为账户名登录

jiangzongyou 2019-12-09 17:35 原文

users.views.py
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
class CustomAuth(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
    try:
        user=UserProfile.objects.get(Q(username=username)|Q(mobile=username))
        if user.check_password(password):
            return user
    # 如果找不到用户,就返回none
    except Exception as e:
        return None
settings.py
AUTHENTICATION_BACKENDS=[
    "apps.users.views.CustomAuth",
]

推荐阅读