Gorgeous thumbnails in Django admin

Short snippet how-to build thumb for some field and show in change list.

I'm going to use sorl-thumbnail.

pip install sorl-thumbnail

Mixin

from sorl.thumbnail import get_thumbnail

class ThumbMixin:
    thumb_size = '100x100'
    thumb_crop = 'center'
    thumb_quality = 99
    thumb_field = 'image'
    thumb_keep_original = False

    def thumb(self):
        field = getattr(self, self.thumb_field, None)
        if field:
            if self.thumb_keep_original:
                return "<a href='{0}' target='_blank'><img src='{1}' alt='' /></a>".format(field.url, field.url)
            else:
                th = get_thumbnail(field, self.thumb_size, crop=self.thumb_crop, quality=self.thumb_quality)
                return "<a href='{0}' target='_blank'><img src='{1}' alt='' /></a>".format(field.url, th.url)
        else:
            return '-'
    thumb.allow_tags = True
    thumb.short_description = 'Thumb'

Test model

from django.db import models
from utils.mixins import ThumbMixin

class Book(ThumbMixin, models.Model):
    title = models.CharField(u'Title', max_length=255)
    photo = PictureField(u'Photo', upload_to=photo_upload_path)

    thumb_field = 'photo'
    thumb_size = '150x150'

    class Meta:
        verbose_name_plural = u'Books'
        verbose_name = u'book'

    def __unicode__(self):
        return self.title

Definition in admin.py

class BookAdmin(admin.ModelAdmin):
    list_display = ('title', 'thumb')
admin.site.register(Book, BookAdmin)
comments powered by Disqus