SoFunction
Updated on 2024-12-10

FBV and CBV for view functions in django in detail

1.What is FBV and CBV

FBV means that the view function is in the form of a normal function; CBV means that the view function is in the form of a class.

2. Common FBV form

def index(request):
return HttpResponse('index')

formality

3.1 Routing in the form of CBV

path(r'^login/',.as_view())

3.2 View functions in CBV form

from  import View
class MyLogin(View):
def get(self,request): Functions executed on #get requests
	return render(request,'')
def post(self,request):  Functions executed on #post requests
	return HttpResponse('post method')

FBV and CBV each have their own merits
CBV features:
Able to match directly to the corresponding method execution based on the different request methods.

source code analysis

The core lies in the routing layer's .as_view() ---> In fact, calling the as_view() function is the same as calling the view() function inside the CBV, because the as_view() function is a closure function that returns the view ----> inside the view function returns the dispatch function ---> The dispatch function calls the corresponding function depending on how the request was made!

Three ways to add decorators

from  import View Modules to be introduced for #CBV
from  import method_decorator # Add modules to be introduced by the decorator
"""
CBV django does not recommend that you add a decorator directly to a class method.
Whether or not the decorator works, it is not recommended to add it directly.
"""

djangofor the benefit ofCBVThree methods are provided to add decorators

# @method_decorator(login_auth,name='get') # way 2 (you can add multiple decorators for different methods)
# @method_decorator(login_auth,name='post')
class MyLogin(View):
    @method_decorator(login_auth)  # 3: It works directly on all the methods of the current class.
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request,*args,**kwargs)
    # @method_decorator(login_auth) # Way 1: Name the method, add login_auth as decorator name directly to the method
    def get(self,request):
        return HttpResponse("get request")

    def post(self,request):
        return HttpResponse('post request')

to this article on the django view function FBV and CBV of the article is introduced to this, more related django view function FBV and CBV content please search my previous posts or continue to browse the following related articles I hope you will support me in the future more!