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

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!


Solution 1:

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`

Solution 2:

This is better

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

else:
    # Action if not existing

Solution 3:

user.groups.all()[0].name == "groupname"

Solution 4:

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