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中的模板中使用Auth应用程序的权限检查吗?(我想在模板末端为特权用户显示一个简单的表单)
And more importantly, should I do it at all or is this no the "Django way"?
更重要的是,我应该这样做吗?还是这不是《被解救的姜戈之路》?
2 个解决方案
#1
125
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.
其中模型指的是用户需要权限才能查看表单的模型。
Refer to https://docs.djangoproject.com/en/stable/topics/auth/default/#permissions for more examples.
更多示例请参考https://docs.djangoproject.com/en/stable/topics/auth/default/#权限。
The currently logged-in user's permissions are stored in the template variable
{{ perms }}
当前登录的用户权限存储在模板变量{{{perms}中
(This requires the following context processor to be enabled: django.contrib.auth.context_processors.auth
)
(这需要启用以下上下文处理器:django.致歉. authb .context_processors.auth)
#2
1
If you need more granularity in checking perms (on a particular object for example), check out this extension: http://django-authority.readthedocs.org/en/latest/check_templates/
如果您需要更细粒度地检查perms(例如在特定对象上),请查看这个扩展:http://django-authority.readthedocs.org/en/latest/check_templates/
#1
125
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.
其中模型指的是用户需要权限才能查看表单的模型。
Refer to https://docs.djangoproject.com/en/stable/topics/auth/default/#permissions for more examples.
更多示例请参考https://docs.djangoproject.com/en/stable/topics/auth/default/#权限。
The currently logged-in user's permissions are stored in the template variable
{{ perms }}
当前登录的用户权限存储在模板变量{{{perms}中
(This requires the following context processor to be enabled: django.contrib.auth.context_processors.auth
)
(这需要启用以下上下文处理器:django.致歉. authb .context_processors.auth)
#2
1
If you need more granularity in checking perms (on a particular object for example), check out this extension: http://django-authority.readthedocs.org/en/latest/check_templates/
如果您需要更细粒度地检查perms(例如在特定对象上),请查看这个扩展:http://django-authority.readthedocs.org/en/latest/check_templates/