Django userAdmin中的用户到组,以及groupAdmin中的group-to-users

时间:2013-11-02 23:16:03

标签: django django-admin

是否可以在用户选项卡的管理面板中包含多对多窗口小部件来选择用户所属的组,以及用于组选项卡中类似的多对多窗口小部件来选择应属于的用户那个小组?

1 个答案:

答案 0 :(得分:7)

简单的方法和艰难的方式。

简单的方法是使用Django的InlineModelAdmin个对象。但是,这样您就无法使用组窗口小部件。

from django.contrib.auth.admin import GroupAdmin
from django.contrib.auth.models import User, Group

class UserSetInline(admin.TabularInline):
    model = User.groups.through
    raw_id_fields = ('user',)  # optional, if you have too many users

class MyGroupAdmin(GroupAdmin):
    inlines = [UserSetInline]

# unregister and register again
admin.site.unregister(Group)
admin.site.register(Group, MyGroupAdmin)

困难的方法要求您构建自己的表单,手动加载并保存相关用户:

from django import forms
from django.contrib import admin
from django.contrib.auth.admin import GroupAdmin
from django.contrib.auth.models import User, Group

class GroupForm(forms.ModelForm):
    users = forms.ModelMultipleChoiceField(
        label='Users',
        queryset=User.objects.all(),
        required=False,
        widget=admin.widgets.FilteredSelectMultiple(
            "users", is_stacked=False))

    class Meta:
        model = Group
        widgets = {
            'permissions': admin.widgets.FilteredSelectMultiple(
                "permissions", is_stacked=False),
        }


class MyGroupAdmin(GroupAdmin):
    form = GroupForm

    def save_model(self, request, obj, form, change):
        # save first to obtain id
        super(GroupAdmin, self).save_model(request, obj, form, change)
        obj.user_set.clear()
        for user in form.cleaned_data['users']:
             obj.user_set.add(user)

    def get_form(self, request, obj=None, **kwargs):
        if obj:
            self.form.base_fields['users'].initial = [o.pk for o in obj.user_set.all()]
        else:
            self.form.base_fields['users'].initial = []
        return GroupForm

# unregister and register again
admin.site.unregister(Group)
admin.site.register(Group, MyGroupAdmin)