问题:在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?
回答 0
您只需通过上的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
然后user.groups.all()
返回[<Group: Editor>]
。
另外,更直接地,您可以通过以下方式检查用户是否在群组中:
if django_user.groups.filter(name = groupname).exists():
...
注意,groupname
它也可以是实际的Django组对象。
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.
回答 1
您的User对象通过ManyToMany关系链接到Group对象。
因此,您可以将filter方法应用于user.groups。
因此,要检查给定的用户是否在某个组中(例如“成员”),只需执行以下操作:
def is_member(user):
return user.groups.filter(name='Member').exists()
如果要检查给定用户是否属于多个给定组,请使用__in运算符,如下所示:
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
希望有帮助
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
Hope this help
回答 2
如果需要组中的用户列表,则可以改为:
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
检查用户是否在组中。
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.
回答 3
如果您不需要网站上的用户实例(就像我一样),可以使用
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.
回答 4
如果用户属于某个组,则可以使用以下方法在Django模板中进行检查:
{% if group in request.user.groups.all %}
"some action"
{% 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 %}
回答 5
您只需要一行:
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!")
回答 6
万一您想检查用户的组是否属于预定义的组列表,以防万一:
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
回答 7
我有类似的情况,我想测试用户是否在某个组中。因此,我创建了新文件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.
回答 8
一行:
'Groupname' in user.groups.values_list('name', flat=True)
这等于True
或False
。
In one line:
'Groupname' in user.groups.values_list('name', flat=True)
This evaluates to either True
or False
.
回答 9
我已经按照以下方式完成了。似乎效率低下,但我心中没有其他选择:
@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')
回答 10
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
回答 11
我是这样做的。对于名为的组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 %}