【问题标题】:Add users to groups in Django将用户添加到 Django 中的组
【发布时间】:2015-06-30 11:13:29
【问题描述】:

我在 Django 中使用 Group 模块。

我创建了视图 GroupCreateViewGroupUpdateView,我可以在其中更新权限和组名,但我还想将用户添加到组中。

现在我必须更新每个用户对象并设置它所属的组。我想用另一种方式来创建组并将用户添加到该组。

这是如何获得的?我想这类似于group.user_set.add(user)

【问题讨论】:

标签: python django django-models django-forms django-views


【解决方案1】:

我假设您想自动将新创建的用户添加到现有组。如果我错了,请纠正我,因为您的问题中没有说明这一点。

这是我在 views.py

中的内容
from django.views.generic.edit import CreateView
from django.contrib.auth.models import User
from django.contrib.auth.models import Group
from django.core.urlresolvers import reverse

class UserCreate(CreateView):
    model = User
    fields = ['username'] #only expose the username field for the sake of simplicity add more fields as you need

    #this one is called when a user has been created successfully
    def get_success_url(self):
        g = Group.objects.get(name='test') # assuming you have a group 'test' created already. check the auth_user_group table in your DB
        g.user_set.add(self.object)
        return reverse('users')  #I have a named url defined below

在我的 urls.py 中:

urlpatterns = [
    url(r'list$', views.UserList.as_view(), name='users'), # I have a list view to show a list of existing users
]

我在 Django 1.8 中对此进行了测试(我确信它也适用于 1.7)。我验证了在 auth_user_group 表中创建了组关系。

附:我还发现了这个:https://github.com/tomchristie/django-vanilla-views/tree/master,它可能对您的项目有用。

【讨论】:

    猜你喜欢
    • 2011-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-21
    • 2017-05-25
    • 1970-01-01
    • 2011-07-10
    • 2016-07-05
    相关资源
    最近更新 更多