在django中添加用户到组

lfapxunr  于 2023-04-22  发布在  Go
关注(0)|答案(4)|浏览(142)

如何通过组名将用户添加到django中的组?
我可以这样做:

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

我该如何做这样的事情:

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

xqk2d5yq1#

使用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)
0x6upsns

0x6upsns2#

以下是如何在Django的现代版本中做到这一点(在Django 1.7中测试):

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

7eumitmz3#

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
u4dcyp6a

u4dcyp6a4#

您可以使用set方法为一个用户分配多个组:

from django.contrib.auth.models import Group

users = Group.objects.get(name="user")
managers = Group.objects.get(name="manager")
user.groups.set([users, managers])

相关问题