CVi的答案适用于一些小调整,但对于我的用例,我真的想要另一个多选小部件来管理组中的用户,就像管理组权限的多选一样.
用这个答案获得灵感,我想出了这个:
from django import forms from django.contrib import admin from django.contrib.auth.admin import GroupAdmin as origGroupAdmin from django.contrib.auth.models import Group, User class GroupAdminForm(forms.ModelForm): """ ModelForm that adds an additional multiple select field for managing the users in the group. """ users = forms.ModelMultipleChoiceField( User.objects.all(), widget=admin.widgets.FilteredSelectMultiple('Users', False), required=False, ) def __init__(self, *args, **kwargs): super(GroupAdminForm, self).__init__(*args, **kwargs) if self.instance.pk: initial_users = self.instance.user_set.values_list('pk', flat=True) self.initial['users'] = initial_users def save(self, *args, **kwargs): kwargs['commit'] = True return super(GroupAdminForm, self).save(*args, **kwargs) def save_m2m(self): self.instance.user_set.clear() self.instance.user_set.add(*self.cleaned_data['users']) class GroupAdmin(origGroupAdmin): """ Customized GroupAdmin class that uses the customized form to allow management of users within a group. """ form = GroupAdminForm # Register the modified GroupAdmin with the admin site admin_site = admin.AdminSite(name='my_admin') admin_site.register(Group, GroupAdmin)