I tried following Code with the help of the django.contrib.auth.User and django.contrib.auth.Group
for g in request.user.groups
This is better
if user.groups.filter(name='groupname').exists():
# Action if existing
else:
# Action if not existing
user.groups.all()[0].name == "groupname"
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
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`