流程
1.authenticate调用的是_get_backends函数
def authenticate(request=None, **credentials):
for backend, backend_path in _get_backends(return_tuples=True):
pass
2._get_backends,默认使用全局配置
def _get_backends(return_tuples=False):
backends = []
for backend_path in settings.AUTHENTICATION_BACKENDS:
pass
3.global_settings.py 使用django.contrib.auth.backends下的ModelBackend的类
django\conf\global_settings.py
AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend']
class ModelBackend:
def authenticate(self, request, username=None, password=None, **kwargs):
pass
重写(实现username或email登录验证)
可以在项目的setting中重写设定
AUTHENCICATION_BACLENDS = ['users.views.CustomBackend',]
users下的views.py
from django.contrib.auth.backends import ModelBackend
from .models import UserProfile
from django.db.models import Q
class CustomBackend(ModelBackend):
def authenticate(self, request, 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
# UserProfile继承AbstractUser
当调用auth中的authenticate将执行上面的方法
from django.contrib.auth import authenticate
def user_login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username,password=password)
# .......