在 Django 中,如何检查用户是否在某个组中? [英] In Django, how do I check if a user is in a certain group?

查看:42
本文介绍了在 Django 中,如何检查用户是否在某个组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I created a custom group in Django's admin site.

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

In my code, I want to check if a user is in this group. How do I do that?

推荐答案

您可以简单地通过 User 上的 groups 属性访问组.

You can access the groups simply through the groups attribute on User.

from django.contrib.auth.models import User, Group

group = Group(name = "Editor")
group.save()                    # save this new group for this example
user = User.objects.get(pk = 1) # assuming, there is one initial user 
user.groups.add(group)          # user is now in the "Editor" group

然后 user.groups.all() 返回 [].

或者,更直接地,您可以通过以下方式检查用户是否在组中:

Alternatively, and more directly, you can check if a a user is in a group by:

if django_user.groups.filter(name = groupname).exists():

    ...

请注意,groupname 可以是实际的 Django Group 对象.

Note that groupname can also be the actual Django Group object.

这篇关于在 Django 中,如何检查用户是否在某个组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆