![7aade70a9cd9721a68706108165df8ad.png](https://img-blog.csdnimg.cn/img_convert/7aade70a9cd9721a68706108165df8ad.png)
![cd0e8ee1f59ac47176fbbe86e7b12908.png](https://img-blog.csdnimg.cn/img_convert/cd0e8ee1f59ac47176fbbe86e7b12908.png)
在进行登录时默认需要使用username以及password字段,如果想要使用telephone、email字段配合密码登录则需要自定义认证类了
![593e71ca9eab6527603a720448e6f07d.png](https://img-blog.csdnimg.cn/img_convert/593e71ca9eab6527603a720448e6f07d.png)
实现原理
Django框架中通过django.conf.global_settings.py配置了项目默认认证类
AUTHENTICATION_BACKENDS= ['django.contrib.auth.backends.ModelBackend']
其中ModelBackend 类就是项目默认认证类
在类中对authenticate方法进行了重写方法中需要针对用户名、密码与数据库进行匹配
如果匹配成功返回当前用户即认证成功 否则认证失败
一、 新建自定义认证类
在应用根目录新建 auth.py
编写自定义认证类
from django.contrib.auth.backends import BaseBackend
from .models import User
from django.db.models import Q
class MyLoginBackend(BaseBackend):
def authenticate(self, request, **kwargs):
username = kwargs["username"]
user = User.objects.filter(Q(email=username) | Q(telephone=username) | Q(username=username) ).first()
if user:
if user.check_password(kwargs["password"]):
return user
return None
在自定义的MyLoginBackend类中对authenticate方法进行重写,提取kwargs中的参数,参数的值即为登录时提交的内容,可以那用户名与用户名、邮箱、手机号等字段进行匹配,有一个匹配成功即开始进行密码的匹配
Q查询是django中自带的查询包装条件,适合多个条件进行或且非逻辑判断
二、配置自定义认证类
在settings.py中添加配置
# 自定义认证类
AUTHENTICATION_BACKENDS=("shop.auth.MyLoginBackend",)
![60750472ac015d6805644ad0adf6e1be.png](https://img-blog.csdnimg.cn/img_convert/60750472ac015d6805644ad0adf6e1be.png)