有没有一种简单的方法可以在 django 中获取用户的组名
我尝试在 django.contrib.auth.User 和 django.contrib.auth.Group 的帮助下遵循代码,
for g in request.user.groups:
l.append(g.name)
但是失败了,我收到了以下错误< /strong>:
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
感谢您的帮助!
I tried following Code with the help of the django.contrib.auth.User and django.contrib.auth.Group
for g in request.user.groups:
l.append(g.name)
But that failed and I received following Error:
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
Thanks for any help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用
request.user.groups.all()
获取用户的组,这将返回一个QuerySet
。然后,如果需要,您可以将该对象转换为列表。或者最近的 Django
You can get the groups of a user with
request.user.groups.all()
, which will return aQuerySet
. And then you can turn that object into a list if you want.or with recent Django
这更好
This is better
这可能有点太晚了(我刚刚加入 stackoverflow),但是对于 2018 年初通过谷歌搜索的人来说,您可以使用 django Groups 对象(默认情况下)附带以下字段(不是详尽的,只是重要的字段)这一事实):
请注意,一个组可以由多个用户组成,一个用户可以是多个组的成员。因此,您可以简单地过滤当前用户会话的 django Groups 模型(确保您已添加相关组并将用户分配到他/她的组):
This is probably tad bit too late (I just joined stackoverflow), but for anyone googling for this in early 2018, you can use the fact that django Groups object (by default) comes with the following fields (not exhaustive , just the important ones):
Note that a group can consist of many users, and a user can be a member of many groups. So you can simply filter the django Groups model for the current user-session (make sure you have added the relevant groups and assigned the user to his/her group/s):
您也可以使用此选项
在你看来
在 yourpage.html 中
this will display all users with their group
You can also use this option
In you views
In yourpage.html
this will display all users with their group