FBV-----function based view 基於函數的視圖
CBV-----class based view 基於類的視圖html
<body> <form action=""method="post"> {% csrf_token %} <input type="text" name="user"> <input type="password" name="pwd"> <input type="submit" > </form> </body>
from django.contrib import admin from django.urls import path from app01 import views urlpatterns = [ path('admin/', admin.site.urls), path('login/', views.LoginView.as_view()), ]
from django.shortcuts import render,HttpResponse from django.views import View class LoginView(View): def get(self,request): return render(request,"login.html") def post(self,request): return HttpResponse("ok") def delete(self,request): pass def put(self,request): pass
點擊提交-----post請求---頁面顯示ok前端
爲何get請求走get方法?=====》看源碼django
咱們先看:後端
path('login/', views.login), #views.login 返回一個函數對象====》一旦login/匹配成功,執行這個函數對象
======對比=======
path('login/', views.LoginView.as_view()), #LoginView.as_view()類。方法==============》views.LoginView.as_view()必定也會返回一個函數對象===》咱們只須要看返回的究竟是不是函數對象
咱們去View類中找as_view()app
關鍵代碼:(爲何咱們訪問就能之間進get、post方法呢?)函數
path('login/', View.as_view.view) # 用戶訪問get請求/login/-----------view(request) --------------------------------------------- def view(request): self = cls(**initkwargs) return self.dispatch(request, *args, **kwargs) --------------------------------------------------------- def dispatch(request, *args, **kwargs): if request.method.lower() in self.http_method_names: handler = getattr(self, request.method.lower(), self.http_method_not_allowed) else: handler = self.http_method_not_allowed return handler(request, *args, **kwargs) #反射找get\post\put方法
補充:post
(1)改寫url
實際上CBV模式就是基於反射 實現根據請求方式不一樣,執行不一樣的方法spa
(2)3d
(3)
from django.views import View class LoginView(View): def dispatch(self, request, *args, **kwargs): print("==========") super().dispatch(request, *args, **kwargs) def get(self,request): return render(request,"login.html")注意這樣會報錯的,由於沒有返回值