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")

 

posted @ 2018-03-20 10:55  SSSupreme  阅读(4185)  评论(0编辑  收藏  举报