Milano
Milano

Reputation: 18705

Show group members in Django Admin

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})

Upvotes: 7

Views: 5639

Answers (2)

PaulR
PaulR

Reputation: 670

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)

Upvotes: 19

CVi
CVi

Reputation: 71

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.

Upvotes: 6

Related Questions