About Editing Users at a Group in Administration

To add user selection at group editing in administration, you would need to create a custom app with admin.py containing a custom model form for the group admin:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
from django import forms
from django.utils.translation import gettext_lazy as _
from django.contrib import admin
from django.contrib.admin.widgets import FilteredSelectMultiple
from django.contrib.auth.models import User, Group
from django.contrib.auth.admin import GroupAdmin as BaseGroupAdmin

admin.site.unregister(Group)

class GroupAdminForm(forms.ModelForm):
    users = forms.ModelMultipleChoiceField(
        queryset=User.objects.all(),
        required=False,
        widget=FilteredSelectMultiple(
            verbose_name=_("Users"), is_stacked=False
        ),
    )

    class Meta:
        model = Group
        fields = ["name", "permissions", "users"]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        if self.instance and self.instance.pk:
            self.fields["users"].initial = self.instance.user_set.all()

    def _save_m2m(self):
        super()._save_m2m()
        role = self.instance
        for user in role.user_set.all():
            user.groups.remove(role)
        for user in self.cleaned_data["users"]:
            user.groups.add(role)

@admin.register(Group)
class GroupAdmin(BaseGroupAdmin):
    form = GroupAdminForm

Tips and Tricks Programming Django 4.x Django 3.2 Django 2.2