1. 程式人生 > >登入認證

登入認證

turn edi 數據庫驗證 .post .get mixin mini str store

一.自定義認證方法

models.py

class Administrator(models.Model):
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=32)

views.py

#登入函數 根據post請求拿到用戶信息,從數據庫驗證後將session的 is_login字段設置成True,並返回默認首頁
def
login(request): message = "" v = request.session print(type(v))
from django.contrib.sessions.backends.db import SessionStore if request.method == "POST": user = request.POST.get(user) pwd = request.POST.get(pwd) c = models.Administrator.objects.filter(username=user, password=pwd).count() if c: request.session[
is_login] = True request.session[username] = user rep = redirect(/index.html) return rep else: message = "用戶名或密碼錯誤" obj = render(request,login.html, {msg: message}) return obj #註銷函數 清除session信息 def logout(request): request.session.clear()
return redirect(/login.html) #驗證裝飾器 def auth(func): def inner(request, *args, **kwargs): is_login = request.session.get(is_login) if is_login: return func(request, *args, **kwargs) else: return redirect(/login.html) return inner

#進入首頁時需要驗證用戶是否登入
@auth
def index(request):
pass

二.Django自帶的登入

from django.views import View
from django.contrib.auth.mixins import LoginRequiredMixin
from  django.contrib import auth
from django.contrib.auth.decorators import login_required
def login(request): if request.method=="GET": error_msg="請登錄" return render(request,index/login.html,{"error_msg":error_msg}) if request.method=="POST": username = request.POST.get("username", "") password = request.POST.get("password", "")
#驗證用戶名密碼 user
=auth.authenticate(username=username,password=password)
if user:
#驗證後用戶登入
auth.login(request,user)
return render(‘index.html‘)
# auth.logout() 用戶退出

#CBV 模式的認證 繼承系統的認證視圖
class index(LoginRequiredMixin,View):
def get(request):
pass
#FBV 模式的認證   django自帶的裝飾器
@login_required
def index(request):
    pass

登入認證