Mezzanine + Sorl.Thumbnail

I really like Mezzanine and use it all the time in projects. It powers this site you’re on now. There are a couple of things that often “bug” me about it though. One is that I don’t understand why Stephen chose to bake his own thumbnail plugin and didn’t just use sorl.thumbnail. Sorl is much more flexible and powerful. For instance I can add margin and center an image when resizing it to give uniform whitespace around images while preserving the aspect ratio, something the built in thumbnail tag can’t do. Sorl also allows me to specify a file type. For instance on a big site I just launched all the header images were added as png images and were huge, over 1MB in size. I needed to convert those to optimized jpeg images and sorl.thumbnail allowed me to do that, reducing the size 10 times to less than 100k with no discernible drop in quality. Again, you can’t do that with the built in thumbnail tag that I know of.

Trouble is that the built in thumbnail tag is used all over the place already in templates and while I could replace sorl with all of those that would be a pain in the behind. Instead I wanted to be able to use both. Here is how you can use the built in thumbnail tag and sorl.thumbnail in Mezzanine templates at the same time.

The first thing we need is a really cool package that adds some functionality to Django’s {% load %} tag. Since both sorl and the built in thumbnail define a thumbnail template tag and we need a way to have more flexibility in importing template tags. Let’s install that library.

pip install django-smart-load-tag

If you haven’t already you’ll need to install sorl as well of course.

pip install sorl-thumbnail

Add both of them to your installed apps

INSTALLED_APPS = (
    ...,
    'sorl.thumbnail',
    'smart_load_tag',
    )

Make sure and run syncdb after installing sorl as it requires a cache to operate correctly and will fail without it.

Now in you template import sorl separately like the following example:

{% load smart_load %}
{% load thumbnail from sorl.thumbnail as sorl_thumbnail %}
...

<img src="{{ MEDIA_URL }}{% sorl_thumbnail page.category.hero_image "1400x300" as im %}{{ im }}{% endthumbnail %}">

That’s it. You can now use both sorl.thumbnail and the built in Mezzanine thumbnail tag in the same template.