7

As we know, ManytoMany relations can't be listed in list_display. Is there any work around to make it like group1, group2 etc?

Hamish Downer
  • 16,603
  • 16
  • 90
  • 84
Siva Arunachalam
  • 7,582
  • 15
  • 79
  • 132

2 Answers2

14

bonus: display group as a user filter:

class SBUserAdmin(UserAdmin):
    list_filter = ("groups")
    list_display = ('username','custom_group', )

    def custom_group(self, obj):
        """
        get group, separate by comma, and display empty string if user has no group
        """
        return ','.join([g.name for g in obj.groups.all()]) if obj.groups.count() else ''

admin.site.unregister(User)
admin.site.register(User, SBUserAdmin)
yretuta
  • 7,963
  • 17
  • 80
  • 151
  • Saweet! Thanks for this slick solution. I should add here another little trick that I added to make it more user friendly: `custom_group.admin_order_field = 'groups'`. This allows to sort on that column: https://docs.djangoproject.com/en/3.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.sortable_by – nicorellius Dec 20 '20 at 21:10
6

I don't understand your example (group1, group2) but you can certainly use any function as a column in the changelist view, which means you can likely do what you want to show!

Example:

class MyModelAdmin(admin.ModelAdmin):
    list_display = ('foo', 'bar')

    def foo(self):
        return "This column is Foo"

    def bar(self, obj):
        try:
            return obj.m2m.latest('id')
        except obj.DoesNotExist:
            return "n/a"


    # there's a few more things you can do to customize this output
    def bar(self, obj):
        return '<span style="color:red;">By the way, I am red.</span>'

    bar.short_description = "My New Column Label"
    bar.allow_tags = True
Yuji 'Tomita' Tomita
  • 115,817
  • 29
  • 282
  • 245
  • in Django >3, if you want to style the cell, you should use : return format_html('By the way, I am red.') otherwise, it's considered as text – agence web JHN Feb 02 '22 at 10:14