Fix Python – Adding a user to a group in django


Asked By – David542

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

Now we will see solution for issue: Adding a user to a group in django


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') 

This question is answered By – juankysmith

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0