Add users to groups in Django

拟墨画扇 提交于 2019-12-02 14:01:22

问题


I am using the Group module in Django.

I've created views GroupCreateView and GroupUpdateView in which I can update permissions and group name, but I also want to add users to the groups.

Right now I have to update each user object and set to which groups it belongs. I want to do it the other way around where I create groups and add users to this group.

How is this obtained? I guess it's something like group.user_set.add(user)


回答1:


I am assuming you want to add a newly created user to an existing group automatically. Correct me if I am wrong since this is not stated in your question.

Here is what I have in 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

In my urls.py:

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

I tested this in Django 1.8 (I am sure it works in 1.7 as well). I verified the group relationship been created in auth_user_group table.

P.S. I have also found this: https://github.com/tomchristie/django-vanilla-views/tree/master which might be useful for your project.



来源:https://stackoverflow.com/questions/29803608/add-users-to-groups-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!