[Django]-How to display inline elements in list_display?

4πŸ‘

βœ…

As you say, defining a function is the way to go – a custom method on the ModelAdmin class which takes the object as a parameter and returns a string representation of the latest comments:

class ArticleAdmin(admin.ModelAdmin):
    list_display = ('name', 'latest_comments')

    def latest_comments(self, obj):
        return '<br/>'.join(c.comment for c in obj.comment_set.order_by('-date')[:3])
    latest_comments.allow_tags = True

This takes the last three comments on each article, sorted by the β€˜date’ field, and displays the comment field of each one, separated by an HTML <br> tag to show on one each line.

Leave a comment