Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 304
Sivasubramaniam Arunachalam Avatar asked Mar 07 '11 20:03

Sivasubramaniam Arunachalam


2 Answers

bonus: display group as a user filter:

class SBUserAdmin(UserAdmin):
    list_filter = UserAdmin.list_filter + ('groups__name',)
    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)
like image 129
yretuta Avatar answered Sep 19 '22 21:09

yretuta


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
like image 27
Yuji 'Tomita' Tomita Avatar answered Sep 19 '22 21:09

Yuji 'Tomita' Tomita