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

前端 未结 4 579
独厮守ぢ
独厮守ぢ 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: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`
    

提交回复
热议问题