Django 自带登录验证:authenticate和login,login_require,logout模块

验证之前需要在settings 中指定验证数据models

AUTH_USER_MODEL = 'crm.UserProfile'#app名字.表名字

1.authenticate是一个方法,验证账号密码是否正确,需要提供username和password2个参数.,验证成功返回一个user对象,失败则返回None:

2.验证完成之后并没有登录,需要用到登录模块,也是一个方法,接受request对象和authenticate返回的user对象.

from django.contrib.auth import login,authenticate,logout
from django.contrib.auth.decorators import login_required

def acc_login(req):
    error=''
    print("-----------",login_required)
    if req.method=="GET":
        return render(req,"acc_login.html")
    else:

        _email=req.POST.get("acc")
        _pwd=req.POST.get("pwd")
        user=authenticate(username=_email,password=_pwd)#验证:返回验证对象,失败则是None
        if user:
            login(req,user)
            next_url = req.GET.get("next", '../index')
            return redirect(next_url)
        else:
            error="账号或者密码错误"
            return render(req, "acc_login.html",{'error':error})

3.登录成功之后我们一般会做session判断,自己写也可以,Django为我们封装好了login_require模块,直接用:

from django.contrib.auth.decorators import login_required

#然后在需要验证的网页前面加上这个装饰器,

@login_required
def xxx(req,):...

#settings 里面指定login_url,如果没有登录就会套转到该路径

LOGIN_URL="/crm/acc_login"

#如果没有登录django跳转到LOGIN_URL,会在GET信息中加上原本地址,方便登录后跳转回原地址.在login 里面合理设置:
def acc_login(req):
    error=''
    print("-----------",login_required)
    if req.method=="GET":
        return render(req,"acc_login.html")
    else:

        _email=req.POST.get("acc")
        _pwd=req.POST.get("pwd")
        user=authenticate(username=_email,password=_pwd)#验证:返回验证对象,失败则是None
        if user:
            login(req,user)
            next_url = req.GET.get("next", '../index')
            return redirect(next_url)
       else:
            error="账号或者密码错误"
            return render(req, "acc_login.html",{'error':error})

 

4.Django 连登出都考虑到了  logout模块,

from django.contrib.auth import login,authenticate,logout

#前端设置一个url 直接对应该view,logout()接受request,就会登出
def acc_logout(req):
    logout(req)
    return redirect("/crm/acc_login")

 

转载于:https://www.cnblogs.com/guoguojj/p/8607951.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值