Django Views - FBV vs CBV
FBV (Function-Based Views) are views based on functions, where functions are used to handle requests in the view.
CBV (Class-Based Views) are views based on classes, where classes are used to handle requests in the view.
FBV
Function-based views have been used in previous chapters, where functions are used to handle user requests. See the following example:
Routing 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 == "tutorialpro" and pwd == "123456":
return HttpResponse("POST method")
else:
return HttpResponse("POST method 1")
If we access http://127.0.0.1:8000/login/ directly in the browser, the output will be:
GET method
CBV
Class-based views use classes to handle user requests, and different request methods can be handled by different methods within the class, which significantly improves code readability.
The defined class must inherit from the parent class View, so the library needs to be imported:
from django.views import View
Before executing the corresponding request method (get/post/put...), the dispatch method is executed first. The dispatch() method calls the appropriate method based on the request type.
Previously, we learned that Django's URL assigns a request to a callable function, not a class. How is the class-based view implemented? This is mainly achieved through the static method as_view() provided by the parent class View. The as_view method is the external interface for class-based views, returning a view function. After calling, the request is passed to the dispatch method, which then handles different methods based on the request type.
Routing 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 == "tutorialpro" and pwd == "123456":
return HttpResponse("POST method")
else:
return HttpResponse("POST method 1")
If we access http://127.0.0.1:8000/login/ directly in the browser, the output will be:
GET method