简体   繁体   English

Django:如何在管理面板中批量添加用户到组?

[英]Django: how to add users to group in bulk in admin panel?

I want to add many users to group based on filter and my selection in admin panel. 我想基于过滤器和我在管理面板中的选择将许多用户添加到组中。 But the user change list view does not provide such action. 但是用户更改列表视图不提供此类操作。 So is there a way to do this? 那么有没有办法做到这一点? Any snippet or app? 任何片段或应用程序?

No shell please because I hope people other than developers can do it. 请不要使用shell,因为我希望开发人员以外的其他人也可以这样做。 I am surprised Django does not provide a way for such a common task. 令我惊讶的是,Django没有为这种常见任务提供方法。

Thanks! 谢谢!

This can save some time but not flexible. 这样可以节省一些时间,但不灵活。 I can't filter and really "bulk" add. 我无法过滤,而实际上是“批量”添加。

I'm afraid this particular functionality is not yet exposed on the panel. 恐怕该特殊功能尚未在面板上公开。 You'll have to roll your sleeves and open up the shell. 您必须卷起袖子并打开外壳。 You can use the following snippet, just put your filters where .get() and .exclude() are defined. 您可以使用以下代码段,只需将过滤器放在定义.get()和.exclude()的位置即可。

 $ python manage.py shell
    >>> from django.contrib.auth.models import User, Group
    >>> my_group = Group.objects.get(name='groupname')
    >>> my_users = User.objects.filter(<your_filter>)
    >>> for my_user in my_users:
    ...    my_group.user_set.add(my_user)

Create A new Form Like This to add users to group in bulk 创建一个像这样的新表单以将用户批量添加

from django.forms import ModelForm
from django import forms
from django.contrib.auth.models import Group, User

class GroupAdminForm(ModelForm):
    class Meta:
        model = Group

    group_users = forms.ModelMultipleChoiceField(label=u'Usuários deste Grupo', queryset=User.objects.all())

    def __init__(self, *args, **kwargs):
        super(GroupAdminForm, self).__init__(*args, **kwargs)
        users_id = list()
        # Avoid 'No exception supplied' 
        try: 
            users = self.instance.group.user_set.all()
            for u in users:
                users_id.append(u.id)
            if self.fields.has_key('group_users'):
                self.fields['group_users'].initial = users_id
        except Exception, e:
            pass

    def clean(self):
        group = self.cleaned_data['group']
        group.save()
        if group.user_set.all():
            group.user_set.clear()
        try:
            users = self.cleaned_data['group_users']
            for user in users:
                group.user_set.add(user)
        except:
            return self.cleaned_data
        return self.cleaned_data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM