Django's FBV and CBV mode

FBV is handling traffic routing manner url >>> service processing function, CBV is >>> url routing class.

The most commonly used is the FBV mode, you do not have too much to say, directly on the working code of CBV. 

1, CBV url routing of how to write?

 1 from django.contrib import admin
 2 from django.urls import path
 3 from django.conf.urls import url
 4 from app01 import views
 5 
 6 urlpatterns = [
 7     path('admin/', admin.site.urls),
 8     url(r"cbv",views.cbv.as_view()),
 9     url(r"fbv",views.fbv),
10 ]

2, view view CBV in the business processing class how to write?

 1 from django.shortcuts import render,redirect,HttpResponse
 2 from django.views import View
 3 # Create your views here.
 4 def fbv(request):
 5     if request.method=="POST":
 6         return HttpResponse("fbv.post")
 7     return render(request, "FBV.html")
 8 
 9 
10 class cbv(View): 
11     def dispatch(self, request, *args, **kwargs):
12         if request.method=="GET":
13             print("get方式经过dispatch...")
14         else:
15             print("post方式经过dispatch...")
16         result=super(cbv, self).dispatch(request, *args, **kwargs)
17         return result
18 
19     def get(self,request):
20         return render(request, "CBV.html")
21 
22     def post(self,request):
23         return HttpResponse("cbv.post")

Referring to the above specific format of the code, in view of CBV view class, each time the GET or POST method dispatch function will go through, it is possible to customize some GET and POST methods before performing common business logic code in the dispatch process, thereby simplifying code. They can also customize their desired function in the dispatch method.

Guess you like

Origin www.cnblogs.com/sun-10387834/p/12459952.html