is there a simple way to get group names of a user in django

前端 未结 4 576
独厮守ぢ
独厮守ぢ 2021-01-30 12:41

I tried following Code with the help of the django.contrib.auth.User and django.contrib.auth.Group

for g in request.user.groups         


        
相关标签:
4条回答
  • 2021-01-30 13:23

    This is better

    if user.groups.filter(name='groupname').exists():
        # Action if existing
    
    else:
        # Action if not existing
    
    0 讨论(0)
  • 2021-01-30 13:24
    user.groups.all()[0].name == "groupname"
    
    0 讨论(0)
  • 2021-01-30 13:24

    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):

    id, name, permissions, user (can have many users; ManyToMany)

    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):

    '''
    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
    
    0 讨论(0)
  • 2021-01-30 13:36

    You can get the groups of a user with request.user.groups.all(), which will return a QuerySet. And then you can turn that object into a list if you want.

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

    or with recent Django

    l = request.user.groups.values_list('name',flat = True) # QuerySet Object
    l_as_list = list(l)                                     # QuerySet to `list`
    
    0 讨论(0)
提交回复
热议问题