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?
As of Django 1.9, you can use
format_html(),format_html_join(), orallow_tagsin your method. See thelist_displaydocs for more info.The code in the question using
mark_safewill work. However a better option for methods like these might beformat_html, which will escape arguments.In earlier versions of Django, using
mark_safe()would not work, and Django would escape the output. The solution was to give the method anallow_tagsattribute with the value set to True.