Django admin and showing thumbnail images


Question

I'm trying to show thumbnail images in Django admin, but I can only see the path to the images, but not the rendered images. I don't know what I'm doing wrong.

Server media URL:

from django.conf import settings
(r'^public/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}),

Function model:

def image_img(self):
        if self.image:
            return u'<img src="%s" />' % self.image.url_125x125
        else:
            return '(Sin imagen)'
        image_img.short_description = 'Thumb'
        image_img.allow_tags = True

admin.py:

class ImagesAdmin(admin.ModelAdmin):

    list_display= ('image_img','product',) 

And the result:

<img src="http://127.0.0.1:8000/public/product_images/6a00d8341c630a53ef0120a556b3b4970c.125x125.jpg" />
1
47
12/19/2015 9:12:45 AM

Accepted Answer

This is in the source for photologue (see models.py, slightly adapted to remove irrelevant stuff):

def admin_thumbnail(self):
    return u'<img src="%s" />' % (self.image.url)
admin_thumbnail.short_description = 'Thumbnail'
admin_thumbnail.allow_tags = True

The list_display bit looks identical too, and I know that works. The only thing that looks suspect to me is your indentation - the two lines beginning image_img at the end of your models.py code should be level with def image_img(self):, like this:

def image_img(self):
    if self.image:
        return u'<img src="%s" />' % self.image.url_125x125
    else:
        return '(Sin imagen)'
image_img.short_description = 'Thumb'
image_img.allow_tags = True
69
3/11/2011 4:41:09 PM

Update v. 1.9

Note that in Django v.1.9

image_tag.allow_tags = True

is depricated and you should use format_html(), format_html_join(), or mark_safe() instead

So your model.py should look like this:

...
def image_img(self):
    if self.image:
        return marksafe('<img src="%s" />' % self.image.url_125x125)
    else:
        return '(Sin imagen)'
    image_img.short_description = 'Thumb'

and in your admin.py add:

list_display= ('image_img','product',)
readonly_fields = ('image_img',)

and for adding it in the 'Edit mode' of your admin panel in your admin.py add:

fields = ( 'image_img', )

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon