我在 django.contrib.auth.User 和 django.contrib.auth.Group
的帮助下尝试使用Codefor g in request.user.groups:
l.append(g.name)
但是失败了,我收到了以下错误:
TypeError at /
'ManyRelatedManager' object is not iterable
Request Method: GET
Request URL: http://localhost:8000/
Exception Type: TypeError
Exception Value:
'ManyRelatedManager' object is not iterable
Exception Location: C:\p4\projects\...\users.py in permission, line 55
感谢您的帮助!
答案 0 :(得分:75)
for g in request.user.groups.all():
l.append(g.name)
或最近的django
l = request.user.groups.values_list('name',flat=True)
答案 1 :(得分:11)
这是更好的
if user.groups.filter(name='groupname').exists():
# Action if existing
else:
# Action if not existing
答案 2 :(得分:7)
user.groups.all()[0].name == "groupname"
答案 3 :(得分:3)
这可能有点太晚了(我刚加入了stackoverflow),但对于在2018年初使用Google搜索的人来说,你可以使用django Groups对象(默认情况下)带有以下字段的事实(并非详尽无遗,只是重要的):
id,name,permissions,user(可以拥有多个用户; ManyToMany)
请注意,组可以包含许多用户,用户可以是许多组的成员。因此,您只需过滤当前用户会话的 django群组模型(确保您已添加相关群组并将用户分配到他/她的群组):
'''
This assumes you have set up django auth properly to manage user logins
'''
# import Group models
from django.contrib.auth.models import Group
# filter the Group model for current logged in user instance
query_set = Group.objects.filter(user = request.user)
# print to console for debug/checking
for g in query_set:
# this should print all group names for the user
print(g.name) # or id or whatever Group field that you want to display