Search code examples
djangodjango-admindjango-authentication

Django - User admin - adding groups to list_display


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


Solution

  • 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