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

发布于 2024-10-13 19:34:50 字数 68 浏览 5 评论 0原文

我在 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

左岸枫 2024-10-20 19:34:50

您的User对象通过ManyToMany关系链接到Group对象。

因此,您可以将filter方法应用于user.groups

因此,要检查给定用户是否属于某个特定组(例如“成员”),只需执行以下操作:

def is_member(user):
    return user.groups.filter(name='Member').exists()

如果要检查给定用户是否属于多个给定组,请使用 __in< /strong> 运算符,如下所示:

def is_in_multiple_groups(user):
    return user.groups.filter(name__in=['group1', 'group2']).exists()

请注意,这些函数可以与 @user_passes_test 装饰器一起使用来管理对视图的访问:

from django.contrib.auth.decorators import login_required, user_passes_test

@login_required
@user_passes_test(is_member) # or @user_passes_test(is_in_multiple_groups)
def myview(request):
    # Do your processing

对于基于类的视图,您可以将 UserPassesTestMixintest_func 方法:

from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin

class MyView(LoginRequiredMixin, UserPassesTestMixin, View):

    login_url = '/login/'
    redirect_field_name = 'redirect_to'

    def test_func(self):
        return is_member(self.request.user)

希望有帮助

Your User object is linked to the Group object through a ManyToMany relationship.

You can thereby apply the filter method to user.groups.

So, to check if a given User is in a certain group ("Member" for the example), just do this :

def is_member(user):
    return user.groups.filter(name='Member').exists()

If you want to check if a given user belongs to more than one given groups, use the __in operator like so :

def is_in_multiple_groups(user):
    return user.groups.filter(name__in=['group1', 'group2']).exists()

Note that those functions can be used with the @user_passes_test decorator to manage access to your views :

from django.contrib.auth.decorators import login_required, user_passes_test

@login_required
@user_passes_test(is_member) # or @user_passes_test(is_in_multiple_groups)
def myview(request):
    # Do your processing

For class based views, you might use UserPassesTestMixin with test_func method:

from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin

class MyView(LoginRequiredMixin, UserPassesTestMixin, View):

    login_url = '/login/'
    redirect_field_name = 'redirect_to'

    def test_func(self):
        return is_member(self.request.user)

Hope this help

2024-10-20 19:34:50

您只需通过 User 上的 groups 属性即可访问组。

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() 返回 []

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

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

    ...

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

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

then user.groups.all() returns [<Group: Editor>].

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

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

    ...

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

眼泪也成诗 2024-10-20 19:34:50

如果您不需要现场的用户实例(就像我一样),您可以使用

User.objects.filter(pk=userId, groups__name='Editor').exists()

这将只产生一个对数据库的请求并返回一个布尔值。

If you don't need the user instance on site (as I did), you can do it with

User.objects.filter(pk=userId, groups__name='Editor').exists()

This will produce only one request to the database and return a boolean.

茶色山野 2024-10-20 19:34:50

如果您需要某个组中的用户列表,您可以这样做:

from django.contrib.auth.models import Group
users_in_group = Group.objects.get(name="group name").user_set.all()

然后检查

 if user in users_in_group:
     # do something

该用户是否在该组中。


更新 2023

10 年后再看这个解决方案,我非常确定我不想像这样获取完整的用户列表。如果规模扩大的话,就会出现问题。您只想在非常特定的用例中获取用户列表,在该用例中可以保证用户列表保持较小,或者您只是使用 Django shell。

If you need the list of users that are in a group, you can do this instead:

from django.contrib.auth.models import Group
users_in_group = Group.objects.get(name="group name").user_set.all()

and then check

 if user in users_in_group:
     # do something

to check if the user is in the group.


Update 2023

Looking at this solution 10 years later, I'm pretty sure that I would NOT want to ever to fetch a whole list of users like this. It's something that would be problematic at scale. You would only want to fetch a list of users in a very specific use case where there were assurances that the list of users was going to remain small, or if you were just using the Django shell.

街角卖回忆 2024-10-20 19:34:50

用户是否属于某个组,可以使用以下命令在 django 模板中检查:

{% if group in request.user.groups.all %}
“一些动作”
{% endif %}

If a user belongs to a certain group or not, can be checked in django templates using:

{% if group in request.user.groups.all %}
"some action"
{% endif %}

っ〆星空下的拥抱 2024-10-20 19:34:50

你只需要一行:

from django.contrib.auth.decorators import user_passes_test  

@user_passes_test(lambda u: u.groups.filter(name='companyGroup').exists())
def you_view():
    return HttpResponse("Since you're logged in, you can see this text!")

You just need one line:

from django.contrib.auth.decorators import user_passes_test  

@user_passes_test(lambda u: u.groups.filter(name='companyGroup').exists())
def you_view():
    return HttpResponse("Since you're logged in, you can see this text!")
吻泪 2024-10-20 19:34:50

使用这个:

{% for group in request.user.groups.all %}
    {% if group.name == 'GroupName' %}
    {% endif %}
{% endfor %}

Use this:

{% for group in request.user.groups.all %}
    {% if group.name == 'GroupName' %}
    {% endif %}
{% endfor %}
猫腻 2024-10-20 19:34:50

我有类似的情况,我想测试用户是否属于某个组。因此,我创建了新文件 utils.py,其中放置了所有可以帮助我完成整个应用程序的小实用程序。在那里,我有了这样的定义:

utils.py

def is_company_admin(user):
    return user.groups.filter(name='company_admin').exists()

所以基本上我正在测试用户是否在 company_admin 组中,为了清楚起见,我将此函数称为 is_company_admin

当我想检查用户是否在 company_admin 中时,我只需这样做:

views.py

from .utils import *

if is_company_admin(request.user):
        data = Company.objects.all().filter(id=request.user.company.id)

现在,如果您想在模板中测试相同的内容,您可以在上下文中添加 is_user_admin ,像这样:

views.py

return render(request, 'admin/users.html', {'data': data, 'is_company_admin': is_company_admin(request.user)})

现在您可以在模板中评估您的响应:

users.html

{% if is_company_admin %}
     ... do something ...
{% endif %}

简单而干净的解决方案,基于可以在本线程前面找到的答案,但以不同的方式进行。希望它能帮助某人。

在 Django 3.0.4 中测试。

I have similar situation, I wanted to test if the user is in a certain group. So, I've created new file utils.py where I put all my small utilities that help me through entire application. There, I've have this definition:

utils.py

def is_company_admin(user):
    return user.groups.filter(name='company_admin').exists()

so basically I am testing if the user is in the group company_admin and for clarity I've called this function is_company_admin.

When I want to check if the user is in the company_admin I just do this:

views.py

from .utils import *

if is_company_admin(request.user):
        data = Company.objects.all().filter(id=request.user.company.id)

Now, if you wish to test same in your template, you can add is_user_admin in your context, something like this:

views.py

return render(request, 'admin/users.html', {'data': data, 'is_company_admin': is_company_admin(request.user)})

Now you can evaluate you response in a template:

users.html

{% if is_company_admin %}
     ... do something ...
{% endif %}

Simple and clean solution, based on answers that can be found earlier in this thread, but done differently. Hope it will help someone.

Tested in Django 3.0.4.

情绪少女 2024-10-20 19:34:50

以防万一您想检查用户的组是否属于预定义的组列表:

def is_allowed(user):
    allowed_group = set(['admin', 'lead', 'manager'])
    usr = User.objects.get(username=user)
    groups = [ x.name for x in usr.groups.all()]
    if allowed_group.intersection(set(groups)):
       return True
    return False

Just in case if you wanna check user's group belongs to a predefined group list:

def is_allowed(user):
    allowed_group = set(['admin', 'lead', 'manager'])
    usr = User.objects.get(username=user)
    groups = [ x.name for x in usr.groups.all()]
    if allowed_group.intersection(set(groups)):
       return True
    return False
不再让梦枯萎 2024-10-20 19:34:50

一行:

'Groupname' in user.groups.values_list('name', flat=True)

计算结果为 TrueFalse

In one line:

'Groupname' in user.groups.values_list('name', flat=True)

This evaluates to either True or False.

明月松间行 2024-10-20 19:34:50

我已经按照以下方式完成了。看起来效率很低,但我心里没有其他办法:

@login_required
def list_track(request):

usergroup = request.user.groups.values_list('name', flat=True).first()
if usergroup in 'appAdmin':
    tracks = QuestionTrack.objects.order_by('pk')
    return render(request, 'cmit/appadmin/list_track.html', {'tracks': tracks})

else:
    return HttpResponseRedirect('/cmit/loggedin')

I have done it the following way. Seems inefficient but I had no other way in my mind:

@login_required
def list_track(request):

usergroup = request.user.groups.values_list('name', flat=True).first()
if usergroup in 'appAdmin':
    tracks = QuestionTrack.objects.order_by('pk')
    return render(request, 'cmit/appadmin/list_track.html', {'tracks': tracks})

else:
    return HttpResponseRedirect('/cmit/loggedin')
笛声青案梦长安 2024-10-20 19:34:50

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

该查询将通知您用户:“tom”是否属于组“admin”

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

That query will inform you user : "tom" whether belong to group "admin " or not

魄砕の薆 2024-10-20 19:34:50

我就是这样做的。对于名为 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 %}

I did it like this. For group named 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)

template

# index.html
{% if is_editor %}
  <h1>Editor tools</h1>
{% endif %}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文