Django Views - FBV and CBV

FBV(function base views)Function-based views use functions in views to handle requests.

CBV(class base views)Class-based views use classes in views to handle requests.

FBV

In fact, we have been using function-based views throughout the previous chapters—that is, using functions to handle user requests. See the following example:

Route configuration:

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 method")
    if request.method == "POST":
        user = request.POST.get("user")
        pwd = request.POST.get("pwd")
        if user == "example" and pwd == "123456":
            return HttpResponse("POST method")
        else:
            return HttpResponse("POST method 1")

If we directly access http://127.0.0.1:8000/login/ in the browser, the output is:

GET 方法

CBV

Class-based views use classes to handle user requests. Different requests can be handled by different methods within the class, greatly improving code readability.

The defined class must inherit from the parent class View, so you need to import the library first:

from django.views import View

Before executing the method corresponding to the request, the dispatch method is executed first (before the get/post/put... methods). The dispatch() method calls the appropriate method to handle the request based on the request type.

Actually, from what we learned earlier, we know that Django's URL maps a request to a callable function, not a class. So how does it implement class-based views? It mainly uses the static method as_view() provided by the parent class View. The as_view method is the external interface of the class-based view. It returns a view function. After being called, the request is passed to the dispatch method, which then handles different methods according to the request type.

Route configuration:

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 method")

    def post(self,request):
        user = request.POST.get("user")
        pwd = request.POST.get("pwd")
        if user == "example" and pwd == "123456":
            return HttpResponse("POST method")
        else:
            return HttpResponse("POST method 1")

If we directly access http://127.0.0.1:8000/login/ in the browser, the output is:

GET 方法
other extensions