Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

django

admin

I've got a model (Entry) which contains a simple property:

@property
def image(self):
        return str(self.id)+"_"+self.round.season.name+"_"+self.round.theme+"_"+self.person.name

I use this to build the name of a particular image file on disk. So I know that there's going to be an image at /path/to/images/(model.image()).jpg

I can display the raw image property itself within the TabularInline layout on an admin page by adding it to the readonly_fields collection, but how would I go about getting a column which had custom html wrapped around the model property?

e.g.

<img src="/images/{{model.image}}.jpg" />
like image 779
growse Avatar asked Mar 09 '11 16:03

growse


1 Answers

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)
like image 61
gladysbixly Avatar answered Oct 16 '22 11:10

gladysbixly