gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 16:29:02 27 4
gpt4 key购买 nike

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

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

关于python - Django - 将参数传递给 CBV 装饰器的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33953468/

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