from django import forms from django.contrib import admin from django.contrib.admin.widgets import FilteredSelectMultiple from django.contrib.auth.admin import GroupAdmin from django.contrib.auth.models import Group,User
classGroupAdminForm(forms.ModelForm): users = forms.ModelMultipleChoiceField(queryset=User.objects.all(), widget=FilteredSelectMultiple('Users', False), required=False) classMeta: model = Group def__init__(self, *args, **kwargs): instance = kwargs.get('instance', None) if instance isnotNone: initial = kwargs.get('initial', {}) initial['users'] = instance.user_set.all() kwargs['initial'] = initial super(GroupAdminForm, self).__init__(*args, **kwargs) defsave(self, commit=True): group = super(GroupAdminForm, self).save(commit=commit) if commit: group.user_set = self.cleaned_data['users'] else: old_save_m2m = self.save_m2m defnew_save_m2m(): old_save_m2m() group.user_set = self.cleaned_data['users'] self.save_m2m = new_save_m2m return group
classMyGroupAdmin(GroupAdmin): form = GroupAdminForm