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

Django - Correct way to pass arguments to CBV decorators?

文档功能 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'

你应该使用 @method_decorator with class methods:

A method on a class isn’t quite the same as a standalone function, so you can’t just apply a function decorator to the method – you need to transform it into a method decorator first. The method_decorator decorator transforms a function decorator into a method decorator so that it can be used on an instance method.

然后只需使用您需要的参数调用装饰器并将其传递给方法装饰器(通过调用可以接受参数的装饰器函数,您将在退出时获得实际的装饰器)。如果您要装饰 class 而不是 class 方法,请不要忘记将要装饰的方法的名称传递为关键字参数 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'