Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a user to a group in django

Tags:

python

django

People also ask

How do I give permission to groups in Django?

With Django, you can create groups to class users and assign permissions to each group so when creating users, you can just assign the user to a group and, in turn, the user has all the permissions from that group. To create a group, you need the Group model from django. contrib. auth.

What is user Group in Django?

Django does provide groups and permissions option but this is a model or table level and not at the object level. Hence we decided on creating groups based on the objects on which we want to provide the access and the users were added to these groups as per requirement or based on the existing state of an object.


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)

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)

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