Adding a user to a group in django

PythonDjango

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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)

Solution 2 - Python

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)

Solution 3 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavid542View Question on Stackoverflow
Solution 1 - PythonjuankysmithView Answer on Stackoverflow
Solution 2 - PythoncoredumperrorView Answer on Stackoverflow
Solution 3 - PythonVigneshKarthik KasiviswanathanView Answer on Stackoverflow