在Django中,如何检查用户是否属于某个组?

195

我在Django的管理网站中创建了一个自定义组。

在我的代码中,我想要检查一个用户是否在这个组中。我该怎么做?

13个回答

0
一行代码:
'Groupname' in user.groups.values_list('name', flat=True)

这将评估为


4
这样做效率很低,因为它会取回更多的数据,然后在 Django 的一侧对其进行操作。最好使用 .exists() 让数据库来完成工作。 - WhyNotHugo

0

User.objects.filter(username='tom', groups__name='admin').exists()

这个查询会告诉你用户“tom”是否属于“admin”组。


groups__name,双下划线 - Trung Lê

0
我是这样做的。对于名为Editor的组。
# views.py
def index(request):
    current_user_groups = request.user.groups.values_list("name", flat=True)
    context = {
        "is_editor": "Editor" in current_user_groups,
    }
    return render(request, "index.html", context)

模板

# index.html
{% if is_editor %}
  <h1>Editor tools</h1>
{% endif %}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接