Django - 将参数传递给CBV装饰器的正确方法?

时间:2015-11-27 08:49:04

标签: python django django-class-based-views python-decorators django-generic-views

文档功能nice options for applying decorators such as login_required to Class Based Views

但是,我有点不清楚如何将特定参数与装饰器一起传递,在这种情况下我想change the login_url of the decorator

如下所示,仅有效:

@login_required(login_url="Accounts:account_login")
@user_passes_test(profile_check)
class AccountSelectView(TemplateView):
    template_name='select_account_type.html'

1 个答案:

答案 0 :(得分:3)

您应该使用@method_decorator with class methods

  

类的方法与独立函数不完全相同,所以   你不能只是将函数装饰器应用于方法 - 你需要   首先将它转换为方法装饰器。 method_decorator   装饰器将函数装饰器转换为方法装饰器   它可以在实例方法上使用。

然后只需使用您需要的参数调用装饰器并将其传递给方法装饰器(通过调用可以接受参数的装饰器函数,您将在退出时获得实际的装饰器)。如果要装饰类而不是类方法本身,请不要忘记将要装饰的方法的名称作为关键字参数name(例如dispatch)传递:

@method_decorator(login_required(login_url="Accounts:account_login"),
                  name='dispatch')
@method_decorator(user_passes_test(profile_check), name='dispatch')
class AccountSelectView(TemplateView):
    template_name='select_account_type.html'
相关问题