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

时间:2021-01-02 16:47:48

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

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

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

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

10 个解决方案

#1


73  

You can access the groups simply through the groups attribute on 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

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

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

#2


150  

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

您的用户对象通过许多tomany关系链接到组对象。

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

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

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

因此,要检查给定用户是否属于某个组(例如“Member”),只需这样做:

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 :

如果要检查给定用户是否属于多个给定组,请使用__in操作符,如:

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 :

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

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

Hope this help

希望这有助于

#3


12  

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.

这将只向数据库生成一个请求并返回一个布尔值。

#4


11  

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.

检查用户是否在组中。

#5


9  

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

如果用户是否属于某个组,可以在django模板中使用:

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

{% if group in request.user.groups。所有%}"some action" {% endif %}

#6


7  

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!")

#7


0  

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

#8


0  

In one line:

一行:

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

This evaluates to either True or False.

这个计算结果为真或假。

#9


0  

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')

#10


0  

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

User.objects。过滤器(用户名=‘汤姆’,groups__name = '管理').exists()

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

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

#1


73  

You can access the groups simply through the groups attribute on 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

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

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

#2


150  

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

您的用户对象通过许多tomany关系链接到组对象。

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

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

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

因此,要检查给定用户是否属于某个组(例如“Member”),只需这样做:

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 :

如果要检查给定用户是否属于多个给定组,请使用__in操作符,如:

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 :

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

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

Hope this help

希望这有助于

#3


12  

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.

这将只向数据库生成一个请求并返回一个布尔值。

#4


11  

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.

检查用户是否在组中。

#5


9  

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

如果用户是否属于某个组,可以在django模板中使用:

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

{% if group in request.user.groups。所有%}"some action" {% endif %}

#6


7  

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!")

#7


0  

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

#8


0  

In one line:

一行:

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

This evaluates to either True or False.

这个计算结果为真或假。

#9


0  

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')

#10


0  

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

User.objects。过滤器(用户名=‘汤姆’,groups__name = '管理').exists()

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

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