Display Thumbnails in Django Admin with Sorl Thumbnail

By default in Django 1.5, admin inline images display just the link to the picture:

In our admin.py we have something like:

class ImageInline(AdminImageMixin, admin.TabularInline):
model = Image

class ServiceAdmin(AdminImageMixin, admin.ModelAdmin):
list_display = ('title', 'position', 'get_image_tag')
inlines = (ImageInline,)
The thumbnails aren't there, so, let's display them:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from django.contrib.admin.widgets import AdminFileWidget
from django.utils.safestring import mark_safe
from django.forms import ModelForm
from sorl.thumbnail import get_thumbnail

class AdminImageWidget(AdminFileWidget):
def render(self, name, value, attrs=None):
output = []
if value and getattr(value, "url", None):
t = get_thumbnail(value,'80x80')
output.append('<img src="{}">'.format(t.url))
output.append(super(AdminFileWidget, self).render(name, value, attrs))
return mark_safe(u''.join(output))

class ImageForm(ModelForm):
class Meta:
model = Image
widgets = {
'image': AdminImageWidget,
}

class ImageInline(AdminImageMixin, admin.TabularInline):
model = Image
form = ImageForm

class ServiceAdmin(AdminImageMixin, admin.ModelAdmin):
list_display = ('title', 'position', 'get_image_tag')
inlines = (ImageInline,)

We override the image widget in order to display images thumbnails, you can change its size in line 10. Result:

Now, if for some reason your non-inline images are not showing its thumbnails like below:

You can also override the image widget with the same class showed above (but this time the form goes inside your admin class instead inline class):

class FooForm(ModelForm):
class Meta:
model = Foo
widgets = {
'main_image': AdminImageWidget, # same used above
}

class FooAdmin(AdminImageMixin, admin.ModelAdmin):
form = FooForm

Result:

That's it, give us your feedback in the comments.

Written on April 8, 2014

Share: