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
4条答案
按热度按时间xqk2d5yq1#
使用Group模型和组名查找组,然后将用户添加到user_set
0x6upsns2#
以下是如何在Django的现代版本中做到这一点(在Django 1.7中测试):
7eumitmz3#
coredumperror是对的,但我发现了一件事,我需要分享这一点
u4dcyp6a4#
您可以使用
set
方法为一个用户分配多个组: