如何在TemplateView中放置自定义装饰器

时间:2013-03-03 16:04:49

标签: django class-based-views

我开始将基于函数的视图转换为基于类的视图。这是我第一次使用基于类的视图,所以我真的不知道正确的方法。

FBV的代码:

@auth_check
def thank_you(request):
    return render(request, 'thank_you.html')

CBV的代码:

class ThankYouView(TemplateView):
    template_name = "thank_you.html"

我会把auth_check装饰器放在哪里?我试着将它放在班级的顶部,但我收到了一个错误。然后我在类中创建def并将装饰器放在它的顶部但仍然出现错误。

1 个答案:

答案 0 :(得分:3)

https://docs.djangoproject.com/en/dev/topics/class-based-views/intro/#decorating-the-class

使用基于类的视图,您可以装饰dispatch方法。

from django.utils.decorators import method_decorator

class ThankYouView(TemplateView):
    template_name = "thank_you.html"

    @method_decorator(auth_check)
    def dispatch(self, *args, **kwargs):
        return super(ThankYouView, self).dispatch(*args, **kwargs)