How to check (in template) if user belongs to a group(如何检查(在模板中)用户是否属于某个组)
问题描述
如何在模板中检查用户是否属于某个组?
How to check in template whether user belongs to some group?
在生成 template 的 view 中是可能的,但是如果我想在 base.html 这是一个扩展模板(它没有自己的视图功能)?
It is possible in a view which is generating the template but what if I want to check this in base.html which is an extending template (it does not have it's own view function)?
我的所有模板都扩展了 base.html,因此在每个 view 中检查它并不好.
All of my templates extends base.html so it is not good to check it in each view.
base.html 包含上栏,其中应包含按钮,具体取决于 group 登录用户所在的位置(客户、卖家).
The base.html contains upper bar, which should contain buttons depending on in which group logged user is (Customers, Sellers).
在我的 base.html 中是:
{% if user.is_authenticated %}
这还不够,因为我必须对来自 Customers 的用户和来自 Sellers 的用户采取不同的行动.
which is not enough because I have to act differently to users from Customers and users from Sellers.
所以我想要的是:
{% if user.in_group('Customers') %}
<p>Customer</p>
{% endif %}
{% if user.in_group('Sellers') %}
<p>Seller</p>
{% endif %}
推荐答案
你需要自定义模板标签:
You need custom template tag:
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/
这篇关于如何检查(在模板中)用户是否属于某个组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何检查(在模板中)用户是否属于某个组
基础教程推荐
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
