Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 user into group using Django Admin page? If yes, how?

Now, I'm adding programatically customers into customers group and sellers 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})
like image 927
Milano Avatar asked Jan 02 '16 16:01

Milano


People also ask

What are groups in Django admin?

Groups are a means of categorizing users. This allows for granting permissions to a specific group.

Can we customize Django admin panel?

The Django admin is a powerful built-in tool giving you the ability to create, update, and delete objects in your database using a web interface. You can customize the Django admin to do almost anything you want.


2 Answers

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)
like image 66
PaulR Avatar answered Sep 22 '22 02:09

PaulR


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.

like image 27
CVi Avatar answered Sep 22 '22 02:09

CVi