From bedda66949e2812faa1270048b0ce8fe940cf75d Mon Sep 17 00:00:00 2001 From: Oliver Walters Date: Sat, 3 Oct 2020 17:37:20 +1000 Subject: [PATCH] Add custom admin view for the "Group" model - Ref: https://github.com/Microdisseny/django-groupadmin-users - Adds ability to edit users within a particular group from the group admin page! --- InvenTree/InvenTree/settings.py | 1 + InvenTree/users/admin.py | 67 ++++++++++++++++++++++++++++++++- 2 files changed, 66 insertions(+), 2 deletions(-) diff --git a/InvenTree/InvenTree/settings.py b/InvenTree/InvenTree/settings.py index f9e3285781..21b8a0ead1 100644 --- a/InvenTree/InvenTree/settings.py +++ b/InvenTree/InvenTree/settings.py @@ -138,6 +138,7 @@ INSTALLED_APPS = [ 'part.apps.PartConfig', 'report.apps.ReportConfig', 'stock.apps.StockConfig', + 'users.apps.UsersConfig', # Third part add-ons 'django_filters', # Extended filter functionality diff --git a/InvenTree/users/admin.py b/InvenTree/users/admin.py index b12fa73f94..00e3ec7040 100644 --- a/InvenTree/users/admin.py +++ b/InvenTree/users/admin.py @@ -1,3 +1,66 @@ # -*- coding: utf-8 -*- -# from __future__ import unicode_literals -# from django.contrib import admin +from __future__ import unicode_literals + +from django.utils.translation import ugettext_lazy as _ + +from django.contrib import admin +from django import forms +from django.contrib.auth import get_user_model +from django.contrib.admin.widgets import FilteredSelectMultiple +from django.contrib.auth.models import Group + +User = get_user_model() + + +class InvenTreeGroupAdminForm(forms.ModelForm): + + class Meta: + model = Group + exclude = [] + fields = [ + 'users', + 'permissions', + ] + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + if self.instance.pk: + # Populate the users field with the current Group users. + self.fields['users'].initial = self.instance.user_set.all() + + # Add the users field. + users = forms.ModelMultipleChoiceField( + queryset=User.objects.all(), + required=False, + widget=FilteredSelectMultiple('users', False), + label=_('Users'), + ) + + def save_m2m(self): + # Add the users to the Group. + # Deprecated in Django 1.10: Direct assignment to a reverse foreign key + # or many-to-many relation + + self.instance.user_set.set(self.cleaned_data['users']) + + def save(self, *args, **kwargs): + # Default save + instance = super().save() + # Save many-to-many data + self.save_m2m() + return instance + + +class RoleGroupAdmin(admin.ModelAdmin): + """ + Custom admin interface for the Group model + """ + + form = InvenTreeGroupAdminForm + + filter_horizontal = ['permissions'] + + +admin.site.unregister(Group) +admin.site.register(Group, RoleGroupAdmin)