PS: Add decorator to CBV
def wrapper(func):
def inner(*args,**kwargs):
return func(*args,**kwargs)
return inner
#1. Add a decorator to the specified method
class Foo(View):
@method_decorator(wrapper)
def get(self,request):
pass
def post(self,request):
pass
2. Add on the class
@method_decorator(wrapper,name='dispatch')
class Foo(View):
def get(self,request):
pass
def post(self,request):
pass
#CBV code
# 1. Routing system urlpatterns = [ url(r'^login.html$', views.Login.as_view()), ] # 2.views类 """ get check post creation put update delete delete """ #Automatically execute the corresponding function according to the method of request.method. #We can rewrite the dispatch function to achieve a similar effect as a decorator, and the dispatch internally implements function execution according to reflection. from django.views import View class Login(View): def get(self,request): return render(request, "login.html") def post(self, request): name = request.POST.get("user") print(name) return HttpResponse("from post ") def dispatch(self, request, *args, **kwargs): print("-----before------") ret = super().dispatch(request,*args,**kwargs) print("-----after------") return ret # # CBV application decorator # django bug, you cannot decorate the class directly, you must use method_decorator, and pass the decorator as a parameter. from django.utils.decorators import method_decorator @method_decorator(wrapper, name="post")