在 django 中向组添加用户

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

我能做到:

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

我怎么会做这种事:

user.groups.add(name='groupname') # add by name
126790 次浏览

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

以下是 Django 的现代版本(在 Django 1.7中进行了测试) :

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

CoreDumperror 是正确的,但我发现了一件事情,我需要分享这一点

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