icn
icn

Reputation: 17876

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!

Upvotes: 69

Views: 110712

Answers (5)

Endalew Simie
Endalew Simie

Reputation: 1

You can also use this option In you views

  users =User.objects.all().exclude(is_superuser=True)
    context = {'users':users}
    return render(request,'yourpage.html',context)

In yourpage.html

{% for users in users %}
  <tr>
    <td>{{users.username}}</td>
    <td>{{users.email}}</td>
    <td>
        {%for group in users.groups.all %}
        {{ group.name }}
        {%endfor%}
    </td>
this will display all users with their group

Upvotes: 0

MattH
MattH

Reputation: 38247

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`

Upvotes: 143

aaronlhe
aaronlhe

Reputation: 1132

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

Upvotes: 12

Dean Christian Armada
Dean Christian Armada

Reputation: 7364

This is better

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

else:
    # Action if not existing

Upvotes: 41

Kishor Pawar
Kishor Pawar

Reputation: 3526

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

Upvotes: 13

Related Questions