以下是使用不同方式为Django中的Class-Based Views添加装饰器的示例:
装饰器函数方式
from django.contrib.auth.decorators import login_requiredfrom django.utils.decorators import method_decoratorfrom django.views.generic import TemplateView@method_decorator(login_required, name='dispatch')class MyView(TemplateView):
template_name = 'my_template.html'
装饰器类方式
from django.contrib.auth.decorators import login_requiredfrom django.utils.decorators import method_decoratorfrom django.views.generic import TemplateViewclass LoginRequiredMixin: @method_decorator(login_required)
def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs)class MyView(LoginRequiredMixin, TemplateView):
template_name = 'my_template.html'
装饰器方法方式
from django.contrib.auth.decorators import login_requiredfrom django.views.generic import TemplateViewclass MyView(TemplateView):
template_name = 'my_template.html'
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs)