【问题标题】:is there a simple way to get group names of a user in django有没有一种简单的方法可以在 django 中获取用户的组名
【发布时间】:2011-01-15 19:07:52
【问题描述】:

我尝试在 django.contrib.auth.Userdjango.contrib.auth.Group

的帮助下遵循代码
for 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

感谢您的帮助!

【问题讨论】:

    标签: python django django-admin


    【解决方案1】:

    您可以使用request.user.groups.all() 获取用户的组,这将返回QuerySet。然后,您可以根据需要将该对象转换为列表。

    for g in request.user.groups.all():
        l.append(g.name)
    

    或使用最近的 Django

    l = request.user.groups.values_list('name',flat = True) # QuerySet Object
    l_as_list = list(l)                                     # QuerySet to `list`
    

    【讨论】:

    • 在第二种情况下,在 print() 上打印一个 QuerySet。第一个 sn-p 将返回预期的平面列表。 (django 2.1.7)
    【解决方案2】:
    user.groups.all()[0].name == "groupname"
    

    【讨论】:

    • 这与问题有什么关系?
    • 是的,与当前问题无关,但它帮助其他人获得了具有特定名称的组。
    【解决方案3】:

    这样更好

    if user.groups.filter(name='groupname').exists():
        # Action if existing
    
    else:
        # Action if not existing
    

    【讨论】:

    • 最短的事实是荒谬的
    【解决方案4】:

    这可能有点太晚了(我刚刚加入 stackoverflow),但对于任何在 2018 年初搜索此内容的人来说,您可以使用 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
    

    【讨论】:

      猜你喜欢
      • 2011-03-02
      • 2012-01-25
      • 2022-01-07
      • 2015-05-12
      • 2011-01-27
      • 1970-01-01
      • 1970-01-01
      • 2017-07-05
      • 2012-08-19
      相关资源
      最近更新 更多