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

默认方法:

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

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

#login登陆函数此处为了防止错乱,改为了login_
def login_(request):
    if request.method=='POST':
        user_name = request.POST.get("username",'')
        pass_word = request.POST.get("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,'login.html',{'msg':'账号或密码错误!'})#返回页面提示错误
    elif request.method=='GET':
        return render(request,'login.html')

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

from django.contrib.auth.backends import ModelBackend#引入ModelBackend方法(用户认证相关)
from django.db.models 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 = UserProfile.objects.get(Q(username=username)|Q(email = username))#|Q()是并行比较,逗号是进行行比较
            if user.check_password(password):#把密码同user数据库内进行比较
                return user
        except Exception as e:
            return None

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

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

 

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学渣王菜菜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值