CBV 与 FBV
FBV:function based view
视图函数,是指之前用的 views.py 中基于函数的开发,url 都是通过函数来实现的,每个 url 对应的函数之间都是独立的。
直接在views.py 中,每个路径请求都是通过 def index(request):实现,如果遇到,请求的分支,通过 if 语句进行判断来处理
CBV:class based view
视图类:是指把有联系的函数放到同一个类中,类中是通过请求来进行分支的,
以登录为例进行简单介绍:
# urls.py
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()) # 重点 必须选中类后要 .as_view() 得到的是 小view函数对象 ]
# views.py
from django.shortcuts import render,HttpResponse # Create your views here. from django.views import View # 创建的来要继承该类 class LoginView(View): def dispatch(self, request, *args, **kwargs): print("dispatch.....") ret=super().dispatch(request, *args, **kwargs) return ret def get(self,request): print("GET....") return render(request,"login.html") def post(self,request): print("post.....") return HttpResponse("OK") def delete(self,request): pass def put(self,request): pass
#login.py
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <form action="" method="post"> {% csrf_token %} <input type="text" name="user"> <input type="text" name="pwd"> <input type="submit"> </form> </body> </html> # login.html