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:
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.2 Django 3.2 Django 2.2
Also by me
Django Paddle Subscriptions app
For Django-based SaaS projects.
Django GDPR Cookie Consent app
For Django websites that use cookies.