问题:将用户添加到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)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。