Adding a user to a group in django

Adding a user to a group in django

How would I add a user to a group in django by the group's name?
I can do this:
user.groups.add(1) # add by id

How would I do something like this:
user.groups.add(name='groupname') # add by name

Solutions/Answers:

Answer 1:

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:

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)

References