Django自定义登录验证类

1.首先在views视图函数内引入

from django.contrib.auth import authenticate
from django.contrib.auth.backends import ModelBackend# 
Q表示查询条件
from django.db.models import Q

ModelBackend即为要重写的验证登录类

2.authenticate会自自动调用重写的类

user = authenticate(request=request,username=email,password=password)

3.重写登录类

class CustomBackend(ModelBackend): 
    def authenticate(self, request, username=None, password=None, **kwargs):   
        try:
            # 可以通过email\mobile....账号进行账号登录
            user = UserProfile.objects.get(Q(email=username)|Q(mobile=username))
            # check_password 验证用户的密码是否正确
            if  user.check_password(password):
                return user
            else:
                return None
        except Exception as e:
            return None

4.settings里面配置

AUTHENTICATION_BACKENDS = (
    'login.views.CustomBackend',
)


你可能感兴趣的:(Django)