2015-04-22 118 views
1

我正在使用Django中的組模塊。將用戶添加到Django中的組

我創建了視圖GroupCreateViewGroupUpdateView,其中我可以更新權限和組名,但我也想將用戶添加到組中。

現在我必須更新每個用戶對象並設置它屬於哪個組。我想以另一種方式創建組並將用戶添加到此組。

這是如何獲得的?我想這有點像group.user_set.add(user)

+0

也許這是你在找什麼:http://stackoverflow.com/questions/6288661/adding-a-user-to-a-group-in-django – Cheng

+0

但是,我怎麼能將它添加到CreateView和更新視圖?我必須創建一個自定義的ModelForm嗎? – Jamgreen

回答

2

我假設你想要一個新創建的用戶添加到現有自動。糾正我,如果我錯了,因爲這不是在你的問題中陳述。

這是我在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這可能對你的項目有用。

相關問題