驗證之前需要在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")
