Django中验证用户账号密码以及登陆账户方法以及验证方法重写(django16)

时间:2025-03-03 12:05:54
默认方法:

Django中验证用户账号密码以及登陆账户方法:
1、引入两个方法:authenticate和login

users/文件
注意:如果你的登陆函数也叫login的话需要改为其他名字,在此处我改为了login_,因为在使用上方引入的login方法的时候,会出问题,为了避免出问题,要改名。
from  import authenticate,login

#login登陆函数此处为了防止错乱,改为了login_
def login_(request):
    if =='POST':
        user_name = ("username",'')
        pass_word = ("password",'')
        #authenticate方法用来验证用户的账号密码是否正确,如果正确,返回User对象,否则返回None
        user = authenticate(username = user_name,password = pass_word)
        if user is not None:#判断是否正确
            login(request,user)#登陆账户
            # 重定向到index主页
            return redirect(index)#重定向到主页,切不可使用render方法,返回的是静态页面,css样式有问题。
        else:
            return render(request,'',{'msg':'账号或密码错误!'})#返回页面提示错误
    elif =='GET':
        return render(request,'')

现在对authenticate方法重写,users/文件

from  import ModelBackend#引入ModelBackend方法(用户认证相关)
from  import Q#引入Q方法

from .models import UserProfile#引入UserProfile方法
# Create your views here.


class CustomBackend(ModelBackend):
    #方法重写
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = (Q(username=username)|Q(email = username))#|Q()是并行比较,逗号是进行行比较
            if user.check_password(password):#把密码同user数据库内进行比较
                return user
        except Exception as e:
            return None

总配置文件:,进行注册。

AUTHENTICATION_BACKENDS =(
    '',
)