Sorl Thumbnail

13.0.0 · active · verified Tue Apr 14

Sorl Thumbnail is a popular and flexible Django application for generating image thumbnails. It handles image resizing, cropping, and caching, offering support for various storage backends (local, S3, Google Cloud Storage) and image processing engines (Pillow, ImageMagick). The current version is 13.0.0, with an active release cadence, typically aligning with Django and Python version updates.

Warnings

Install

Imports

Quickstart

To get started, install `sorl-thumbnail` and `Pillow`, then add `sorl.thumbnail` to your Django `INSTALLED_APPS`. If using the cached database key-value store (the default), run `python manage.py migrate`. You can then use the `ImageField` in your models or the `{% thumbnail %}` template tag to generate and display thumbnails. Remember to configure `MEDIA_ROOT` and potentially `STORAGES` in your Django settings. This quickstart includes a basic Django setup for a runnable example.

import os
import django
from django.conf import settings
from django.core.files.uploadedfile import SimpleUploadedFile
from django.db import models

settings.configure(
    INSTALLED_APPS=[
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'sorl.thumbnail',
        'myapp'
    ],
    DATABASES={
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': ':memory:',
        }
    },
    MEDIA_ROOT=os.path.join(os.path.dirname(__file__), 'media'),
    STATIC_ROOT=os.path.join(os.path.dirname(__file__), 'static'),
    STATIC_URL='/static/',
    THUMBNAIL_KEY_PREFIX='sorl-test-',
    THUMBNAIL_STORAGE='default',
    STORAGES = {
        'default': {
            'BACKEND': 'django.core.files.storage.FileSystemStorage'
        },
        'thumbnails': {
            'BACKEND': 'django.core.files.storage.FileSystemStorage'
        }
    },
    SECRET_KEY=os.environ.get('DJANGO_SECRET_KEY', 'a-very-secret-key-for-testing'),
    TEMPLATES=[
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ],
)
django.setup()

class Item(models.Model):
    image = ImageField(upload_to='items')

    def __str__(self):
        return f"Item {self.pk}"

# --- Example Usage ---
from sorl.thumbnail import get_thumbnail
from django.template import Context, Template

# Create a dummy image file
dummy_image = SimpleUploadedFile("test_image.jpg", b"file_content", content_type="image/jpeg")

# Save an item with the image
item = Item.objects.create(image=dummy_image)

# Generate a thumbnail using the low-level API
thumbnail_obj = get_thumbnail(item.image, '100x100', crop='center', quality=95)
print(f"Generated thumbnail URL: {thumbnail_obj.url}")

# Simulate template rendering (requires a request context usually)
# For a true runnable example without a full Django app, this is tricky.
# This part demonstrates the template tag usage conceptually.
# In a real Django project, you'd put {% load thumbnail %} and the tag in your .html file.

# Example template snippet
template_str = """
{% load thumbnail %}
<img src="{% thumbnail item.image '50x50' crop='center' as im %}{{ im.url }}{% endthumbnail %}">
"""

template = Template(template_str)
context = Context({'item': item})

# This will likely fail without a full Django test setup that handles file storage properly
# print(template.render(context))

# Clean up (optional, for real apps, let Django manage)
item.image.delete(save=False)
item.delete()

view raw JSON →