如何在django中编写自定义装饰器? [英] How to write a custom decorator in django?
问题描述
问题 -
@is_premium_user
def sample_view:
.......
......
我希望只有高级用户该网站。
如何在我的项目中的各种应用程序中使用这个装饰器?
I want certain views accesible to only the premium users of the website.
And how can I use this decorator across various applications in my project?
推荐答案
你不必为自己编写自己的装饰器作为 user_passes_test
已经包含在Django中。
You don't have to write your own decorator for this as user_passes_test
is already included in Django.
还有一个代码片段一个延伸这个装饰器的href =http://djangosnippets.org/snippets/1703/ =nofollow noreferrer> group_required_decorator
)非常适合你的用例。
And there's a snippet (group_required_decorator
) that extends this decorator and which should be pretty appropriate for your use case.
如果你真的想写自己的装饰器,那么有很多好的文档在网上。
If you really want to write your own decorator then there's a lot of good documentation on the net.
而且,(重新)使用装饰器只是将装饰器放在路径上的一个模块中,您可以从任何其他模块导入。
And well, to (re-) use the decorator just put your decorator in a module on your path and you can import it from any other module.
这篇关于如何在django中编写自定义装饰器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!