将用户添加到Django中的组
问题描述:
我正在使用Django中的组模块。将用户添加到Django中的组
我创建了视图GroupCreateView
和GroupUpdateView
,其中我可以更新权限和组名,但我也想将用户添加到组中。
现在我必须更新每个用户对象并设置它属于哪个组。我想以另一种方式创建组并将用户添加到此组。
这是如何获得的?我想这有点像group.user_set.add(user)
答
我假设你想要一个新创建的用户添加到现有组自动。纠正我,如果我错了,因为这不是在你的问题中陈述。
这是我在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表中创建的组关系。
P.S.我也发现这个:https://github.com/tomchristie/django-vanilla-views/tree/master这可能对你的项目有用。
也许这是你在找什么:http://stackoverflow.com/questions/6288661/adding-a-user-to-a-group-in-django – Cheng
但是,我怎么能将它添加到CreateView和更新视图?我必须创建一个自定义的ModelForm吗? – Jamgreen