如何通过群组名称将用户添加到django中的群组?
我可以这样做:
user.groups.add(1) # add by id
我将如何做这样的事情:
user.groups.add(name='groupname') # add by name
答案 0 :(得分:200)
使用组模型查找具有组名称的组,然后将用户添加到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 :(得分:76)
以下是如何在现代版本的Django中进行此操作(在Django 1.7中测试):
from django.contrib.auth.models import Group
group = Group.objects.get(name='groupname')
user.groups.add(group)
答案 2 :(得分:1)
这是在django 1.8.4版本中为用户创建组的答案
from django.contrib.auth.models import Group
group = Group.objects.get(name='groupname')
user.groups.add(group)
答案 3 :(得分:1)
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