12

The admin.py at contrib.auth defines the fields to be displayed for the user at the admin interface:

list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')

I want to see the group of each user here:

enter image description here

Just for testing purpose when you try to add the "group" field it fail:

list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff', 'group')

This error rises: : (admin.E109) The value of 'list_display[5]' must not be a ManyToManyField.

After searching I have found only ways to add an app to the admin interface, or to create a custom user model, but I think I'm missing something.

So, how to do it?

SOLVED --- Thanks to the answer of @{Alexis N-o}

Edit /usr/local/lib/pyton2.7/dist-packages/django/contrib/auth/admin.py

Just before the list_display add this def that seeks for the groups:

def group(self, user):
    groups = []
    for group in user.groups.all():
        groups.append(group.name)
    return ' '.join(groups)
group.short_description = 'Groups'

list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff', 'group')

Then syncdb, and check the change at admin, notice the last column:

enter image description here

3 Answers3

12

It is not possible by default because of the ManyToMany relation but this should work:

def group(self, user):
    groups = []
    for group in user.groups.all():
        groups.append(group.name)
    return ' '.join(groups)
group.short_description = 'Groups'

list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff', 'group')
# The last argument will display a column with the result of the "group" method defined above

You can test it and organize the code to your convenience.

Alexis N-o
  • 3,954
  • 26
  • 34
4

this can help

admin.py

from django.contrib.auth.admin import UserAdmin

from django.contrib.auth.models import User

class UserAdminWithGroup(UserAdmin):
    def group_name(self, obj):
        queryset = obj.groups.values_list('name',flat=True)
        groups = []
        for group in queryset:
            groups.append(group)
        
        return ' '.join(groups)

    list_display = UserAdmin.list_display + ('group_name',)

admin.site.unregister(User)
admin.site.register(User, UserAdminWithGroup)
Muhammadoufi
  • 75
  • 1
  • 6
-1

After reading about ManyToMany fields in admin list_display, it doesn't seem like it's possible without adding custom model methods.

Although, it looks like adding custom methods to built-in Django models is possible, if you do something like this:

from django.contrib.auth.models import User

class UserMethods(User):
  def custom_method(self):
    pass
  class Meta:
    proxy=True

proxy=True being the statement that tells django not to override the original model.

After that, just import your custom model method that gets the groups that are associated with the user and add it to your admin class.

Community
  • 1
  • 1