1. 程式人生 > >day76 auth模塊 用戶驗證,

day76 auth模塊 用戶驗證,

index nbsp authent 驗證 urn auth 創建 username ...

我們的登錄驗證是瀏覽器級別的驗證還有用戶級別的驗證,

使用我們的django內部的數據庫表,auth_user,然後使用它內部的一些模塊和方法,

在視圖函數裏面需要引入模塊寫邏輯代碼:

from django.shortcuts import render,redirect

# Create your views here.

from django.contrib import auth
from django.contrib.auth.models import User
# 以上兩句是固定模式, def log_in(request): if request.method=="POST": user=request.POST.get("user") pwd=request.POST.get("pwd") # 驗證成功,返回user對象,否則返回None user=auth.authenticate(username=user,password=pwd) if user: auth.login(request,user) # session寫操作 return redirect("/index/") return render(request,"login.html") def index(request): print(request.user) print(type(request.user)) # if not request.user.id: # return redirect("/login/") # user=request.user # if not user.is_authenticated():return redirect("/login/") return render(request,"index.html",locals()) def log_out(request): auth.logout(request) return redirect("/login/") def reg(request): User.objects.create_user(username="egon123",password="1234") return redirect("/login/")

在驗證中我們有幾種狀態固定語句:

登錄:

user1=auth.authenticate(username=user,password=pwd)

auth.login(request,user1) # 類似於session寫操作

==============================================================

退出登錄狀態:

auth.logout(request)

request.session.flush()

=================================================

驗證 :

user.is_authenticated()

登錄狀態時,返回True,否則返回False

===================================================

創建用戶:

user.objects.create_user(username=‘egon‘,password=‘1234‘)

沒寫完...................................

day76 auth模塊 用戶驗證,