CBV實現的登陸視圖html
class LoginView(View): def get(self, request): """ 處理GET請求 """ return render(request, 'login.html') def post(self, request): """ 處理POST請求 """ user = request.POST.get('user') pwd = request.POST.get('pwd') if user == 'zk' and pwd == "zk1234": next_url = request.GET.get("next") # 生成隨機字符串 # 寫瀏覽器cookie -> session_id: 隨機字符串 # 寫到服務端session: # { # "隨機字符串": {'user':'zk'} # } request.session['user'] = user if next_url: return redirect(next_url) else: return redirect('/index/') return render(request, 'login.html')
要在CBV視圖中使用咱們上面的check_login裝飾器,有如下三種方式:python
from django.utils.decorators import method_decoratordjango
1. 加在CBV視圖的get或post方法上瀏覽器
from django.utils.decorators import method_decorator class HomeView(View): def dispatch(self, request, *args, **kwargs): return super(HomeView, self).dispatch(request, *args, **kwargs) def get(self, request): return render(request, "home.html") @method_decorator(check_login) def post(self, request): print("Home View POST method...") return redirect("/index/")
2. 加在dispatch方法上cookie
from django.utils.decorators import method_decorator class HomeView(View): @method_decorator(check_login) def dispatch(self, request, *args, **kwargs): return super(HomeView, self).dispatch(request, *args, **kwargs) def get(self, request): return render(request, "home.html") def post(self, request): print("Home View POST method...") return redirect("/index/")
由於CBV中首先執行的就是dispatch方法,因此這麼寫至關於給get和post方法都加上了登陸校驗。session
3. 直接加在視圖類上,但method_decorator必須傳 name 關鍵字參數函數
若是get方法和post方法都須要登陸校驗的話就寫兩個裝飾器。post
from django.utils.decorators import method_decorator @method_decorator(check_login, name="get") @method_decorator(check_login, name="post") class HomeView(View): def dispatch(self, request, *args, **kwargs): return super(HomeView, self).dispatch(request, *args, **kwargs) def get(self, request): return render(request, "home.html") def post(self, request): print("Home View POST method...") return redirect("/index/")
CSRF Token相關裝飾器在CBV只能加到dispatch方法上,或者加在視圖類上而後name參數指定爲dispatch方法。url
備註:spa
from django.views.decorators.csrf import csrf_exempt, csrf_protect from django.utils.decorators import method_decorator class HomeView(View): @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super(HomeView, self).dispatch(request, *args, **kwargs) def get(self, request): return render(request, "home.html") def post(self, request): print("Home View POST method...") return redirect("/index/")
或者
from django.views.decorators.csrf import csrf_exempt, csrf_protect from django.utils.decorators import method_decorator @method_decorator(csrf_exempt, name='dispatch') class HomeView(View): def dispatch(self, request, *args, **kwargs): return super(HomeView, self).dispatch(request, *args, **kwargs) def get(self, request): return render(request, "home.html") def post(self, request): print("Home View POST method...") return redirect("/index/")