[Django]-Django admin TabularInline – is there a good way of adding a custom html column?

40👍

What you can do is create a method in your TabularInline subclass that returns the HTML you want, then use that method’s name in place of image in ImageInline.fields:

from django.utils.safestring import mark_safe

class ImageInline(admin.TabularInline):
    ...
    fields = (..., 'render_image')
    readonly_fields = (..., 'render_image')

    def render_image(self, obj):
        return mark_safe("""<img src="/images/%s.jpg" />""" % obj.image)

20👍

According to current Django 1.2+ I got errors “Form does not have such field as render_image”. Solution is simple put the render_image function into model.Admin not in your inline form, second thing is fields and readonly_fields settings in your Inline form… So here You have what I’ve ended up with:

class OfferPropertyInline(admin.TabularInline):
    model = OfferProperty
    fields=('property_value',)
    readonly_fields = ('property_value',)

class OfferAdmin(admin.ModelAdmin):
    inlines = [
        OfferPropertyInline
    ]

    def property_value(self,obj):
        return obj.get_value()

admin.site.register(Offer, OfferAdmin)
👤lechup

3👍

Lechup’s answer does not work for me, I am using Django 1.11.7. I found this way to work around.

Let say I have 2 tables: Campaign and Article, one campaign has many articles. I want to show the articles when browsing a specific campaign.

Table Article has a column named score, which is a float. I want to round it up to 2 decimal places when viewing in Django admin.

This example shows how you can make a custom column for TabularInline in Django admin.

class Article(models.Model):
    title = models.TextField(null=False)
    url = models.TextField()        
    score = models.FloatField(null=True)

    def __str__(self):
        return self.title

    def display_score(self):
        if self.score:
            return round(self.score, 2)
        return self.score

    display_score.short_description = 'Score'

class ArticleInline(admin.TabularInline):
    model = Article
    readonly_fields = ('title', 'url', 'display_score')
    fields = ('title', 'url', 'display_score')

class CampaignAdmin(admin.ModelAdmin):
    inlines = [ArticleInline]

admin.site.register(Campaign, CampaignAdmin)
👤Quan

0👍

@lechup correct except you need:

readonly_fields = ('mycustomfield',)

defined in the Inline for later versions of django (+1.4)

Leave a comment