Python 在 Django 中,如何检查用户是否在某个组中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4789021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Django, how do I check if a user is in a certain group?
提问by TIMEX
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?
在我的代码中,我想检查一个用户是否在这个组中。我怎么做?
采纳答案by miku
You can access the groups simply through the groupsattribute on User.
您可以简单地通过 上的groups属性访问组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>].
然后user.groups.all()返回[<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 groupnamecan alsobe the actual Django Group object.
请注意,groupname它也可以是实际的 Django Group 对象。
回答by Mark Chackerian
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.
检查用户是否在组中。
回答by James Sapam
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
回答by Charlesthk
Your Userobject is linked to the Groupobject through a ManyToManyrelationship.
您的User对象通过ManyToMany关系链接到Group对象。
You can thereby apply the filtermethod to user.groups.
因此,您可以将过滤器方法应用于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 __inoperator 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_testdecorator to manage access to your views :
请注意,这些函数可以与@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
Hope this help
希望这有帮助
回答by Philipp Zedler
In one line:
在一行中:
'Groupname' in user.groups.values_list('name', flat=True)
This evaluates to either Trueor False.
这评估为True或False。
回答by Marcelo Cintra de Melo
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!")
回答by David Kühner
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.
这将只产生一个对数据库的请求并返回一个布尔值。
回答by CODEkid
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.all %}"some action"{% endif %}
回答by Mohammad
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')
回答by Trung Lê
User.objects.filter(username='tom', groups__name='admin').exists()
User.objects.filter(username='tom', groups__name='admin').exists()
That query will inform you user : "tom" whether belong to group "admin " or not
该查询将通知您用户:“tom”是否属于“admin”组

