将用户添加到Django中的组

问题:将用户添加到Django中的组

如何通过组名将用户添加到django中的组?

我可以做这个:

user.groups.add(1) # add by id

我将如何做这样的事情:

user.groups.add(name='groupname') # add by name

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

回答 0

使用具有组名称的“组模型”查找组,然后将用户添加到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)

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)

回答 1

这是在现代版本的Django(在Django 1.7中测试)中如何执行此操作:

from django.contrib.auth.models import Group
group = Group.objects.get(name='groupname')
user.groups.add(group)

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)