如何在Django模板中显示用户所属的自定义组名称?
在Django模板中显示用户的组名称
嘿,这个需求很常见,我来给你两种实用的解决方案,适配不同的业务场景:
场景1:用户只会属于单个组(比如你的默认free/升级后premium的情况)
因为你设定用户注册默认加入free组,后续大概率也只会在两个组之间切换(不会同时属于多个),可以直接取用户的第一个组名称,同时加上兜底判断避免无组的异常情况:
{% if user.is_authenticated %} <p>Welcome, {{ user.username }}. Thanks for logging in. Your account status is {% if user.groups.all %} {{ user.groups.all.0.name }} {% else %} No group assigned {% endif %} </p> {% else %} <p>Welcome, new user. Please log in.</p> {% endif %}
这里的user.groups.all是Django User模型多对多关联Group的查询集,.0取第一个组的对象,.name就是你在后台创建的组名称(free/premium)。
场景2:用户可能属于多个组(预留扩展场景)
如果之后你的业务允许用户同时属于多个组,用循环遍历所有组会更稳妥,还能自动处理多组的分隔显示:
{% if user.is_authenticated %} <p>Welcome, {{ user.username }}. Thanks for logging in. Your account status(es): {% for group in user.groups.all %} {{ group.name }}{% if not forloop.last %}, {% endif %} {% empty %} No group assigned {% endfor %} </p> {% else %} <p>Welcome, new user. Please log in.</p> {% endif %}
这段代码会把用户所有的组名称用逗号分隔显示,如果没有组就显示兜底文本。
内容的提问来源于stack exchange,提问作者Eric
相关产品推荐
相关产品推荐

