Django中的验证|登录|注销 函数--views中导入django.contrib.auth authenticate()|login()|logout()。

2 篇文章 0 订阅
2 篇文章 0 订阅

django.contrib.auth中的authenticate()|login()|logout()函数使用。
  验证|登录|注销 函数
  authenticate()--登录认证:
    接受两个参数,用户名|username 密码|password 
    合法的情况下返回一个User对象。不合法,返回None。
    用is not None else 判断是否验证成功.
    语法:user=auth.authenticate(username=name,password=pwd)
  login()--用户登录:
    接受两个参数request对象和一个User对象
    并自动保存session与cookie
    语法:auth.login(request,user)
  logout()--注销用户:
    它接受一个request对象并且没有返回值,所以,需要返回一个页面。
    语法:auth.logout(request)

示例 登录认证+登录设置:

def login(request):
    if request.method =='GET':
        # get请求返回登录页面
        return render(request,'login.html')
    if request.method =='POST':
        # post请求接受验证数据
        uname = request.POST.get('uname')
        upwd = request.POST.get('upwd')
        user=auth.authenticate(username=uname,password=upwd)
        if user is not None and user.is_active:
            # 验证通过返回首页
            auth.login(request,user) # session cookie
            return render(request,'index.html')
        else:
            # 验证不通过返回登录页面提示信息
            return render(request,'login.html',{'msg':'用户名或密码错误'})

示例 注销用户:

def logot(request):
    # 注销当前用户并返回首页
    auth.logout(request)
    return render(request,'index.html')

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值