Adding a user to a group in django
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Jungle Looping
--
Chapters
00:00 Adding A User To A Group In Django
00:13 Accepted Answer Score 348
00:28 Answer 2 Score 137
00:42 Answer 3 Score 11
01:04 Answer 4 Score 4
01:16 Thank you
--
Full question
https://stackoverflow.com/questions/6288...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #django
#avk47
    Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Jungle Looping
--
Chapters
00:00 Adding A User To A Group In Django
00:13 Accepted Answer Score 348
00:28 Answer 2 Score 137
00:42 Answer 3 Score 11
01:04 Answer 4 Score 4
01:16 Thank you
--
Full question
https://stackoverflow.com/questions/6288...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #django
#avk47
ACCEPTED ANSWER
Score 348
Find the group using Group model with the name of the group, then add the user to the user_set
from django.contrib.auth.models import Group
my_group = Group.objects.get(name='my_group_name') 
my_group.user_set.add(your_user)
ANSWER 2
Score 137
Here's how to do this in modern versions of Django (tested in Django 1.7):
from django.contrib.auth.models import Group
group = Group.objects.get(name='groupname')
user.groups.add(group)
ANSWER 3
Score 11
coredumperror is right but I have found one thing I need to share that one
from django.contrib.auth.models import Group
# get_or_create return error due to 
new_group = Group.objects.get_or_create(name = 'groupName')
print(type(new_group))       # return tuple
new_group = Group.objects.get_or_create(name = 'groupName')
user.groups.add(new_group)   # new_group as tuple and it return error
# get() didn't return error due to 
new_group = Group.objects.get(name = 'groupName')
print(type(new_group))       # return <class 'django.contrib.auth.models.Group'>
user = User.objects.get(username = 'username')
user.groups.add(new_group)   # new_group as object and user is added
ANSWER 4
Score 4
You can assign multiple groups to a user using the set method:
from django.contrib.auth.models import Group
users = Group.objects.get(name="user")
managers = Group.objects.get(name="manager")
user.groups.set([users, managers])