如何在模板中检查用户是否属于某个组?
在生成 template
的 view
中是可能的,但是如果我想在 base.html
这是一个扩展模板(它没有自己的 View 功能)?
我的所有模板都扩展了 base.html
,因此在每个 view
中检查它并不好。
base.html
包含上栏,其中应包含按钮,具体取决于 group
登录用户所在的位置(客户、卖家)。
在我的 base.html
中是:
{% if user.is_authenticated %}
这还不够,因为我必须对来自 Customers
的用户和来自 Sellers
的用户采取不同的行动。
所以我想要的是:
{% if user.in_group('Customers') %}
<p>Customer</p>
{% endif %}
{% if user.in_group('Sellers') %}
<p>Seller</p>
{% endif %}
最佳答案
您需要自定义模板标签:
from django import template
register = template.Library()
@register.filter(name='has_group')
def has_group(user, group_name):
return user.groups.filter(name=group_name).exists()
在您的模板中:
{% if request.user|has_group:"mygroup" %}
<p>User belongs to my group
{% else %}
<p>User doesn't belong to mygroup</p>
{% endif %}
来源:http://www.abidibo.net/blog/2014/05/22/check-if-user-belongs-group-django-templates/
文档:https://docs.djangoproject.com/en/dev/howto/custom-template-tags/
关于python - 如何检查(在模板中)用户是否属于某个组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34571880/