编写认证类
from django.db.models import Q from django.contrib.auth.backends import ModelBackend from .models import User class UserModelBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): filter_q = Q() filter_q.connector = 'OR' # 用户名登录 filter_q.children.append( Q(('username', username)) ) # 手机号登录 filter_q.children.append( Q(('phone', username)) ) user = User.objects.filter(filter_q).first() if user and user.check_password(password) and self.user_can_authenticate(user): return user
修改配置文件指定认证类
#Django默认认证类 AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend'] #我们自己指定的类 AUTHENTICATION_BACKENDS = [ 'user.utils.LyUserModelBackend' ]