一:CBV如何添加装饰器
1.CBV中django不建议直接给类的方法加装饰器
copy
CBV中django不建议你直接给类的方法加装饰器
无论该装饰器能都正常给你 都不建议直接加
2.CBC添加装饰器的三种方法
copy
方式1:指名道姓
@method_decorator(login_auth)
方式2(可以添加多个针对不同的方法加不同的装饰器)
@method_decorator(login_auth,name='get')
@method_decorator(login_auth,name='post')
方式3:它会直接作用于当前类里面的所有的方法 下面的方法都会有login_auth
@method_decorator(login_auth)
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request,*args,**kwargs)
# 需要导入模块
from django.utils.decorators import method_decorator
3.CBV添加装饰器实战
copy
from django.views import View
from django.utils.decorators import method_decorator
# @method_decorator(login_auth,name='get') # 方式2(可以添加多个针对不同的方法加不同的装饰器)
# @method_decorator(login_auth,name='post')
class MyLogin(View):
@method_decorator(login_auth) # 方式3:它会直接作用于当前类里面的所有的方法 下面的方法都会有login_auth
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request,*args,**kwargs)
# @method_decorator(login_auth) # 方式1:指名道姓
def get(self,request):
return HttpResponse("get请求")
def post(self,request):
return HttpResponse('post请求')
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步