我开始将基于函数的视图转换为基于类的视图。这是我第一次使用基于类的视图,所以我真的不知道正确的方法。
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并将装饰器放在它的顶部但仍然出现错误。
答案 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)