FBV(function base views) A function-based view is to use a function to handle requests in the view.
CBV(class base views) A class-based view is to use classes to handle requests in the view. In fact, we have been using the function-based view in the previous section, that is, we use the function to process the user’s request. Check the following example: Routing configuration: If we access http://127.0.0.1:8000/login/ directly in the browser, the output is as follows: Based on the view of the class, we use the class to handle the user’s request, and we can use different methods to deal with different requests in the class, which greatly improves the readability of the code. The defined class inherits the parent class View, so you need to import the library first: The dispatch method is executed prior to the execution of the corresponding requested method (in get/post/put… Method), the dispatch () method invokes the corresponding method according to the request. In fact, everything we’ve learned before knows that Django’s url assigns a request to a callable function, not a class, so how do you implement a class-based view? Mainly through a static method as_view () provided by the parent class View, the as_view method is based on the external interface of the class, it returns a view function, and the request is passed to the dispatch method, and the dispatch method handles different methods according to different requests. Routing configuration: If we access http://127.0.0.1:8000/login/ directly in the browser, the output is as follows: 7.18.1. FBV ¶
Urls.py file ¶
urlpatterns = [
path("login/", views.login),
]
Views.py file ¶
from django.shortcuts import render,HttpResponse
def login(request):
if request.method == "GET":
return HttpResponse("GET 方法")
if request.method == "POST":
user = request.POST.get("user")
pwd = request.POST.get("pwd")
if user == "runoob" and pwd == "123456":
return HttpResponse("POST 方法")
else:
return HttpResponse("POST 方法1")
GET 方法
7.18.2. CBV ¶
from django.views import View
Urls.py file ¶
urlpatterns = [
path("login/", views.Login.as_view()),
]
Views.py file ¶
from django.shortcuts import render,HttpResponse
from django.views import View
class Login(View):
def get(self,request):
return HttpResponse("GET 方法")
def post(self,request):
user = request.POST.get("user")
pwd = request.POST.get("pwd")
if user == "runoob" and pwd == "123456":
return HttpResponse("POST 方法")
else:
return HttpResponse("POST 方法 1")
GET 方法