开发者

Django - User admin - adding groups to list_display

开发者 https://www.devze.com 2023-02-15 14:24 出处:网络
As we know, ManytoMany relations can\'t be listed in list_display. Is there any work around to make it like gr开发者_如何学编程oup1, group2 etc?bonus: display group as a user filter:

As we know, ManytoMany relations can't be listed in list_display. Is there any work around to make it like gr开发者_如何学编程oup1, group2 etc?


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)


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
0

精彩评论

暂无评论...
验证码 换一张
取 消