Skip to main content

One source image turning into many thumbnails

Django Advance Thumbnail

Thumbnails as a model field. Declare it once, and every save keeps the thumbnail in sync with its source image.

Tests PyPI version Python versions Django versions Monthly downloads MIT license

Installation · Quick start · How it works · Resize methods · Commands · Production notes

Watch on YouTube: Why your AI-built shop is slow on phones
Watch (2:46): Why your AI-built shop is slow on phones
Built your app with an AI assistant? Tell it: "Use django-advance-thumbnail to add thumbnails to my product images."


Why this library

Most thumbnail tools render on request, from template tags. AdvanceThumbnailField instead stores the thumbnail as a real ImageField on your model, generated once at save time. That means:

  • product.thumbnail.url works everywhere: templates, the admin, DRF serializers, any storage backend or CDN.
  • No image processing on page views, and no template tags to learn.
  • The thumbnail follows its source: it is created on save, rebuilt when the source changes, and deleted when the source is cleared.

Pick this library when each image needs one or a few fixed thumbnail sizes, known up front, that you want stored next to the original. Pick something else when sizes are chosen in templates or per request (sorl-thumbnail, easy-thumbnails), or when you need processing pipelines such as filters and watermarks (django-imagekit).

Using an AI coding assistant? Point it at llms.txt, a one-page integration guide with the exact steps, options and gotchas.

Features

Automatic Generated on post_save. No signals or tasks to write.
Smart regeneration Rebuilt only when the source, size or resize_method changes, or the thumbnail is missing.
Two resize modes fit keeps the whole picture. fill returns exact dimensions by center-cropping.
Format aware Keeps JPEG, PNG and WebP (transparency included). Fixes rotation from EXIF.
Thread safe Safe under gunicorn, uWSGI and other multi-threaded servers (v2.0+).
Bulk tools generate_thumbnails and regenerate_thumbnails management commands.
Migration friendly Full deconstruct() support, so field settings appear in migrations.

Installation

pip install django-advance-thumbnail

Add the app to INSTALLED_APPS:

INSTALLED_APPS = [
    # ...
    "django_advance_thumbnail",
]

Quick start

from django.db import models
from django_advance_thumbnail import AdvanceThumbnailField


class Product(models.Model):
    image = models.ImageField(upload_to="products/")
    thumbnail = AdvanceThumbnailField(
        source_field="image",
        upload_to="thumbnails/",
        size=(300, 300),
        null=True,
        blank=True,
    )

Run makemigrations and migrate. Every saved Product now gets a thumbnail:

<img src="{{ product.thumbnail.url }}" alt="{{ product.name }}">

Adding the field to a model that already has rows? Run python manage.py generate_thumbnails once to backfill.

How it works

Save, change check, render with Pillow, store thumbnail

The thumbnail is saved as <source name>_thumbnail<ext> with save(update_fields=[...]), so only the thumbnail column is written back to the database.

Resize methods

A 1600x800 photo: fit gives 300x150, fill gives 300x300 center-cropped

Method Result for a 1600×800 source at size=(300, 300) Use it for
fit (default) 300×150. The whole image, scaled to fit inside the box. Galleries and previews where nothing may be cut off
fill / cover 300×300. Scaled to cover the box, then center-cropped. Grids, avatars and cards that need identical sizes
from django_advance_thumbnail import AdvanceThumbnailField, RESIZE_FIT, RESIZE_FILL

thumbnail = AdvanceThumbnailField(source_field="image", size=(300, 300), resize_method=RESIZE_FILL)

cover is an alias for fill. The constants RESIZE_FIT, RESIZE_FILL and RESIZE_COVER are exported for convenience.

Field options

Option Type Default Description
source_field str required Name of the ImageField to build the thumbnail from
size tuple[int, int] (300, 300) Target (width, height) in pixels
resize_method str "fit" "fit", "fill" or "cover"
force_regenerate bool False Rebuild on every save, even when nothing changed

All standard ImageField options (upload_to, storage, null, blank, …) work as usual. Invalid options raise ImproperlyConfigured at startup, not at runtime.

Several thumbnails per image

class Product(models.Model):
    image = models.ImageField(upload_to="products/")

    # Small, whole image, for listings
    thumbnail_small = AdvanceThumbnailField(
        source_field="image", upload_to="thumbnails/small/",
        size=(100, 100), resize_method="fit", null=True, blank=True,
    )

    # Large, exact size, for the detail page
    thumbnail_large = AdvanceThumbnailField(
        source_field="image", upload_to="thumbnails/large/",
        size=(400, 400), resize_method="fill", null=True, blank=True,
    )

Management commands

generate_thumbnails creates missing thumbnails. Use it after adding the field to existing data.

python manage.py generate_thumbnails                         # every model
python manage.py generate_thumbnails --model shop.Product    # one model
python manage.py generate_thumbnails --model shop.Product --field thumbnail
python manage.py generate_thumbnails --force                 # rebuild existing ones too
python manage.py generate_thumbnails --dry-run               # preview only

regenerate_thumbnails rebuilds the thumbnails that no longer match their field's size or resize_method, plus any that are missing. It checks the image files themselves, so it works after a restart and with any cache backend.

python manage.py regenerate_thumbnails                 # rebuild thumbnails whose size no longer matches
python manage.py regenerate_thumbnails --force         # rebuild everything
python manage.py regenerate_thumbnails --dry-run       # preview only

Both commands accept --model app_label.ModelName and --field name.

Production notes

Change detection. The cache is only a fast path. On a cache miss (a restart, an eviction, or a per-process backend such as LocMemCache), the field compares the stored thumbnail name with the current source instead. So restarts and extra workers do not produce duplicate thumbnails.

That fallback only sees filenames. If you replace a source file under the same name and you have no shared cache (Redis, Memcached), the change is not detected. Run regenerate_thumbnails --force in that case.

Config changes. After changing size or resize_method, run regenerate_thumbnails once (for example, right after deploying). It compares every stored thumbnail with the size the new settings produce and rebuilds only the ones that differ. Saving a row does not rebuild its thumbnail for a config change. Before 2.0.3 the plain command never noticed a config change; on those versions use regenerate_thumbnails --force.

File names. A thumbnail is named after its image and its field: camera_thumbnail.jpg for a field called thumbnail, camera_cart_thumbnail.jpg for cart_thumbnail. Several thumbnails of one image can share an upload_to folder, even on storage that overwrites files with the same name (S3 in django-storages does by default). Before 2.0.3 every thumbnail was named <image>_thumbnail, so give each field its own folder on those versions.

Thread safety. Since v2.0, recursion is prevented with an instance-level flag instead of disconnecting and reconnecting signals. This makes the field safe under multi-threaded servers.

Formats. JPEG, PNG and WebP sources keep their format. Other formats are encoded as JPEG, and transparent images are placed on a white background when saved as JPEG.

Requirements

  • Python 3.6+
  • Django 3.0+
  • Pillow 8.0+

Every push is tested in CI on Python 3.9 – 3.14, Django 3.2 – 6.x and Pillow 8.4 – latest. See CHANGELOG.md for release notes.

Upgrading from 1.x

Version 2.0 makes source_field required, validates options at startup and changes the return value of regenerate_thumbnails(). See MIGRATION_GUIDE.md.

Contributing

Issues and pull requests are welcome.

git clone https://github.com/itsmahadi007/django_advance_thumbnail.git
cd django_advance_thumbnail
pip install -r requirements.txt
pytest

Author

Mahadi Hassan: mahadihassan.com · GitHub · LinkedIn · mh@mahadihassan.com

License

MIT

Metadata

Release files for django-advance-thumbnail 2.0.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-advance-thumbnail 2.0.3
File Size Uploaded Provenance Actions
django_advance_thumbnail-2.0.3.tar.gz 27.4 kB Without provenance Details for django_advance_thumbnail-2.0.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for django-advance-thumbnail 2.0.3
File Interpreter ABI Platform Actions
django_advance_thumbnail-2.0.3-py3-none-any.whl Python 3 none any Details for django_advance_thumbnail-2.0.3-py3-none-any.whl

Total release size: 45.6 kB

Release files / django_advance_thumbnail-2.0.3.tar.gz

Download URL django_advance_thumbnail-2.0.3.tar.gz
Size 27.4 kB
Tags Source
SHA-256 checksum
How to use checksums
eb2cc2c03ae863b7f32783c326985f525afd6d36096847bd6c79ff074acf7666
BLAKE2b-256 checksum
How to use checksums
04581020fa6fcbc97841822f49e1e79eae06781ea5c4ef8141f2127f3a2964ea
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / django_advance_thumbnail-2.0.3-py3-none-any.whl

Download URL django_advance_thumbnail-2.0.3-py3-none-any.whl
Size 18.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
47bd4eced74e5a7f6859d521f5884424d828f8e35e2e562e3efb1314ffa5dfd7
BLAKE2b-256 checksum
How to use checksums
7269825d6f29581fbf367c8998cda6360408caf11a8ff2a5c77982cf575e7ce3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Security for django-advance-thumbnail 2.0.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page