views:

28

answers:

1

Hi, I'm trying to display image thumbnails in django admin's list_display and I am doing it like this:

from django.utils.safestring import mark_safe

class PhotoAdmin(admin.ModelAdmin):
    fields = ('title', 'image',)
    list_display = ('title', '_get_thumbnail',)

    def _get_thumbnail(self, obj):
        return mark_safe(u'<img src="%s" />' % obj.admin_thumbnail.url)

Admin keeps displaying the thumbnail as escaped html, although I marked the string as safe. What am I doing wrong?

+2  A: 

From the Django docs:

If the string given is a method of the model, ModelAdmin or a callable, Django will HTML-escape the output by default. If you'd rather not escape the output of the method, give the method an allow_tags attribute whose value is True.

In your case, try

class PhotoAdmin(admin.ModelAdmin):
    fields = ('title', 'image',)
    list_display = ('title', '_get_thumbnail',)

    def _get_thumbnail(self, obj):
         return u'<img src="%s" />' % obj.admin_thumbnail.url
    _get_thumbnail.allow_tags = True
Alasdair
Thanks you for clarification, I couldn't find it in the docs.
Andy
@Andy, if that works for you, click the check-mark under the score this answer has to accept it.
Dominic Rodger