Show group members in Django Admin
Asked Answered
B

2

7

Is it possible to set Django Admin page to show which user is in which group? And is it possible to be able to add a user into a group using the Django Admin page? If yes, how?

Now, I'm adding programmatically customers into customers group and sellers into sellers group, but I can't see any information in my administration.

This is my registration view:

def register_customer(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        customer_registration_form = forms.CustomerRegistrationForm(request.POST)

        if form.is_valid() and customer_registration_form.is_valid():
            new_user = form.save()
            new_customer_profile = UserCustomerProfile(user=new_user)

            new_customer_profile.save()
            customers_group = Group.objects.get(name='Customers')
            new_user.groups.add(customers_group)

            return render(request, 'registration/complete.html')
        else:
            #handle errors

    customer_registration_form = forms.CustomerRegistrationForm()
    form = UserCreationForm()
    return render(request, "registration/register.html",
                  {'form': form, 'customer_registration_form': customer_registration_form})
Blowhole answered 2/1, 2016 at 16:54 Comment(0)
A
19

CVi's answer worked with some minor tweaks, but for my use case I really wanted another multi-select widget to manage the users in the group just like the multi-select for managing the group's permissions.

Using this answer for inspiration, I came up with this:

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)
Ascription answered 28/4, 2016 at 14:34 Comment(1)
Love love love when someone does my work for me! I got "AlreadyRegistered: The model Group is already registered", so just had to add admin.site.unregister(Group) as I already have an admin site, and I renamed origGroupAdmin to DjangoGroupAdmin just to stick with the upper case class convention. Thank you very much!Quaint
B
6

I'm not sure if this is what you are looking for, but you could make modifications to the ModelAdmin for Group like this (the admin.py of your app):

from django.contrib.auth.admin import GroupAdmin
from django.contrib.auth.models import Group
admin.site.unregister(Group)


class UserInLine(admin.TabularInline):
    model = Group.user_set.through
    extra = 0


@admin.register(Group)
class GenericGroup(GroupAdmin):
    inlines = [UserInLine]

Code based on this answer

Now you may edit the inline as you wish.

I don't think it's exactly what you are looking for, but it is a quick and dirty fix that gets the job done.

Disclaimer: I do not know if this is the approved Django way of doing things, but I believe it is not too far off.

Bascomb answered 2/1, 2016 at 17:30 Comment(1)
For Django 1.8, I needed to use model = User.groups.through as through is not an attribute of Group.user_setAscription

© 2022 - 2024 — McMap. All rights reserved.