6

I would like to change admin for a group, so it would display how many users are there in a certain group. I'd like to display this in the view showing all groups, the one before you enter admin for certain group. Is it possible? I am talking both about how to change admin for a group and how to add function to list_display.

ekad
  • 14,436
  • 26
  • 44
  • 46
gruszczy
  • 40,948
  • 31
  • 128
  • 181

1 Answers1

14

First you'd need to import and subclass GroupAdmin from django.contrib.auth.admin. In your subclass, define a user_count method. Then, unregister the existing Group model from the admin, and re-register the new one.

from django.contrib.auth.admin import GroupAdmin
from django.contrib.auth.models import Group

class GroupAdminWithCount(GroupAdmin):
    def user_count(self, obj):
        return obj.user_set.count()

    list_display = GroupAdmin.list_display + ('user_count',)

admin.site.unregister(Group)
admin.site.register(Group, GroupAdminWithCount)
gruszczy
  • 40,948
  • 31
  • 128
  • 181
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Funny, I already have my own GroupAdmin, just forgot, that I was doing something on that (easier user addition, since you can't add users from default group admin). It was so long time ago, that I simply forgot about that.. Thanks a lot for your help :-) – gruszczy Mar 24 '10 at 14:18
  • Ok, a field appears, but it is always None and user_count function is not called. Any idea, why is this happening? – gruszczy Mar 24 '10 at 14:22
  • Ohk, it should be obj.user_set.count(), rather than self.user_set.count(). Now it works :-) – gruszczy Mar 24 '10 at 14:25
  • Why not defining the function in the model directly ? – Pierre de LESPINAY Jul 22 '11 at 10:57
  • @Glide if it's something you're going to use outside the admin, then sure. But if it's only for use in the admin's list_display, it belongs in the admin class. – Daniel Roseman Jul 22 '11 at 11:03