Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 568
icn Avatar asked Feb 11 '10 16:02

icn


People also ask

What is __ Str__ in Django?

str function in a django model returns a string that is exactly rendered as the display name of instances for that model.

How can I get full name in Django?

You can use {{full_name}} in your Django template. Also, if your user is authenticated you can use {{request. user. get_full_name}} in the template.


1 Answers

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` 
like image 172
MattH Avatar answered Sep 22 '22 06:09

MattH