gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 05:08:35 25 4
gpt4 key购买 nike

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

FBV的代码:

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

CBV的代码:
class ThankYouView(TemplateView):
template_name = "thank_you.html"

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

最佳答案

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

使用基于类的 View ,您可以装饰 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)

关于django - 如何在 TemplateView 中放置自定义装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15187567/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com