检查Django模板中的权限 [英] Check permission inside a template in Django
问题描述
我可以在Django中的模板中使用Auth应用程序的权限检查吗? (我想在特权用户模板的最后一个显示一个简单的表单)
Can I use the Auth application's permission checking inside a template in Django? (I want to display a simple form at the end of the template for privileged users)
更重要的是,我应该这样做,还是这样没有Django方式?
And more importantly, should I do it at all or is this no the "Django way"?
推荐答案
如果您要查看模板中的权限,以下代码就足够了:
If you are looking to check for permissions in templates, the following code would suffice:
{% if perms.app_label.can_do_something %}
<form here>
{% endif %}
其中模型是指用户需要权限的模型请参阅
Where model refers to the model that the user need permissions to see the form for.
请参阅 https://docs.djangoproject.com/en/stable/topics/auth/default/#permissions 了解更多示例。
当前登录的用户权限存储在模板变量 {{perms}}
The currently logged-in user's permissions are stored in the template variable
{{ perms }}
(这需要启用以下上下文处理器: django.contrib.auth.context_processors.auth
)
(This requires the following context processor to be enabled: django.contrib.auth.context_processors.auth
)
这篇关于检查Django模板中的权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!