icn*_*icn 38 python django django-admin
我在django.contrib.auth.User和django.contrib.auth.Group的帮助下尝试使用Code
for g in request.user.groups:
l.append(g.name)
Run Code Online (Sandbox Code Playgroud)
但那失败了,我收到了以下错误:
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
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助!
Mat*_*ttH 82
for g in request.user.groups.all():
l.append(g.name)
Run Code Online (Sandbox Code Playgroud)
或者与最近的django
l = request.user.groups.values_list('name',flat = True) # QuerySet Object
l_as_list = list(l) # QuerySet to `list`
Run Code Online (Sandbox Code Playgroud)
Dea*_*ada 13
这个更好
if user.groups.filter(name='groupname').exists():
# Action if existing
else:
# Action if not existing
Run Code Online (Sandbox Code Playgroud)
这可能有点太晚了(我刚刚加入了 stackoverflow),但是对于 2018 年初在 Google 上搜索此内容的任何人,您可以使用 django Groups 对象(默认情况下)带有以下字段(并非详尽无遗,只是重要的字段)这一事实):
id、名称、权限、用户(可以有多个用户;ManyToMany)
请注意,一个组可以由多个用户组成,一个用户可以是多个组的成员。因此,您可以简单地过滤当前用户会话的django Groups 模型(确保您已添加相关组并将用户分配到他/她的组):
'''
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
Run Code Online (Sandbox Code Playgroud)