Images and Galleries

Django Cast provides comprehensive image handling with automatic responsive image generation, gallery support, and optimized delivery across all devices.

Images

Images are mostly just the normal Wagtail Images. But they are rendered using a picture tag supporting srcset and sizes attributes for responsive images.

Upload GPS privacy

New Wagtail image uploads (including replacement files, admin and editor API uploads, and direct model saves) have the EXIF GPS directory removed before storage. Other EXIF data, including orientation, is retained. Images without EXIF GPS and SVG files are unchanged. GPS-bearing raster images are re-encoded with Pillow; JPEG quantization settings are retained, but the encoding is not lossless. GPS removal supports JPEG, PNG, WebP, AVIF and HEIF. GPS-bearing multi-frame images and other formats (such as TIFF) are rejected rather than flattened or silently stored with GPS. This includes multi-picture JPEGs (MPO), such as phone photos containing HDR gain maps, even when named .jpg. Admin and editor API uploads receive a file validation error for these files.

Cast wraps the configured WAGTAILIMAGES_IMAGE_FORM_BASE during app startup, retaining custom form behavior. Validation sanitizes files before Wagtail stores either a normal image or a deferred multi-upload. Both in-memory and disk-backed uploads are supported; stripped bytes are written back to the upload before storage. Custom upload code that writes files directly through storage or FieldFile.save() must call cast.image_metadata.sanitize_upload() before writing; model signals cannot intercept an earlier direct storage write. Unreadable raster uploads fail before storage. This policy covers EXIF GPS, not location information embedded in XMP, image content, or other metadata.

Existing originals and renditions are not rewritten. To inventory existing Wagtail originals, run:

python manage.py report_image_gps

This read-only command lists each matching image ID and storage name, followed by counts. It opens files through their configured storage backend and never saves images, creates renditions, or changes files or database rows. SVG files are skipped. Missing or unreadable raster files are reported on stderr; the command continues scanning and exits with an error if the report is incomplete. No GPS coordinates are printed. Review and remediate existing files separately.

Responsive Images

Responsive images adapt to different screen sizes, ensuring optimal display across devices. This project uses two types of responsive images:

  • Normal Images: Displayed within page content.

  • Thumbnail Images: Shown as thumbnails in content and enlarged in a modal upon clicking.

Image Renditions: For each image, up to three renditions are created in each configured format (AVIF and JPEG by default):

  • 1x Width: Standard size, used in the src attribute of the img tag.

  • 2x Width: Double size, included only when the original is large enough.

  • 3x Width: Triple size, included only when necessary.

These renditions are specified in the srcset attribute of the related source or img elements.

Normal Images

Normal images fill a slot with a width of 1110px and a maximum height of 740px. But you can configure those values in the settings.

Therefore, if you have an image which is quadratic and has a width of 3000px it will rendered with a maximum width of 740px, but delivered with a width of 2220px to high pixel density devices.

Both AVIF and JPEG formats are supported.

Thumbnail Images

Thumbnail images have a width of 120px and a maximum height of 80px. But you can also set those values in the settings.

They also support AVIF and JPEG formats.

Galleries

Galleries are a collection of images. They are used to display a list of thumbnails and a larger view of the selected image. See responsive images for more information about thumbnails.

Creating Galleries

Galleries are created automatically when images are selected in the StreamField editor. The get_or_create_gallery() function handles this:

  1. It receives a list of image IDs from the editor.

  2. It looks up existing galleries whose image set matches exactly.

  3. If a matching gallery already exists, it is reused.

  4. If no match is found, a new Gallery is created and the images are associated with it.

This deduplication ensures that the same combination of images always references the same gallery object. If none of the provided IDs resolve to existing images, the function returns None.

from cast.models.gallery import get_or_create_gallery

# Returns an existing gallery, creates a new one, or returns None
gallery = get_or_create_gallery([image1.pk, image2.pk, image3.pk])

Galleries in StreamField

Galleries are added to posts via the GalleryBlockWithLayout block, which wraps a list of image-and-caption entries with an optional layout selector:

  • Web Component with Modal (default) – Renders thumbnails using the <image-gallery-bs4> web component with a modal for the full-size view.

  • HTMX based layout – Uses HTMX-powered server-side rendering for the gallery modal navigation.

from cast.blocks import GalleryBlockWithLayout

body = StreamField([
    # ...
    ("gallery", GalleryBlockWithLayout()),
    # ...
])

Each entry has a required image chooser and an optional plain-text caption (up to 250 characters). Captions belong to the entry: the same image may occur multiple times with different captions. They do not change the image title or alternative text. Rich text and caption links are not supported by this field.

Newly saved list items use the following JSON value:

{"type": "item", "id": "entry-uuid", "value": {"image": 123, "caption": "An example"}}

Custom StreamFields serialize the GalleryItemBlock class into their schema migrations so historical models retain the legacy decoder. Keep this import available while those migrations exist.

Legacy integer-valued items remain readable, including old revisions. Saving can rewrite them into structured values, including programmatic and editor-API saves. No bulk content migration is required. Older django-cast versions cannot read newly saved structured items; before allowing edits or imports, retain a content backup for code-and-content rollback. Entry order, repeated images, and list-item IDs are retained. The separate Gallery model remains an image-set cache; captions live in Post.body.

Templates receive gallery_entries containing image and caption for each occurrence. The existing images context is retained for themes that have not adopted captions. Built-in templates render escaped text in figcaption next to the thumbnail; modal captions are not transported. Custom themes must render gallery_entries to display captions. The standalone HomePage gallery retains its image-only editing schema.

During rendering, value.gallery retains image objects for uncaptioned entries; captioned entries contain image and caption mappings. Custom themes should use images for image-only rendering or gallery_entries for a uniform caption-aware representation.

Programmatic Post Updates

Publication prepares built-in media relationships and image renditions automatically. Wagtail previews instead resolve media from the preview body into a request-local lookup, including unsaved admin changes. They may create missing image renditions but do not synchronize stored media links or create Gallery records. A direct model save deliberately has no media I/O. When code changes a post body outside those Wagtail boundaries, prepare its media explicitly after persistence:

from cast.post_media import prepare_post_media

post.body = updated_body
post.save()
prepare_post_media(post)

Publication preparation is synchronous because repository rendering needs the derived relationships and renditions immediately. Preview rendering prepares only missing renditions synchronously, without changing those relationships.

Rendition System Internals

This section describes the rendition pipeline in cast/renditions.py. It is primarily useful for theme developers who need to understand how images are sized and delivered in templates.

Core Types

Rectangle

A dataclass holding width (Width) and height (Height). Represents both image dimensions and slot dimensions. It is hashable so it can be used as a dictionary key.

ImageType

A literal type with two values: "regular" and "gallery". Determines which set of slot dimensions is used (configured via CAST_REGULAR_IMAGE_SLOT_DIMENSIONS and CAST_GALLERY_IMAGE_SLOT_DIMENSIONS).

ImageFormat

A literal type for supported output formats: "jpeg", "avif", "webp", "png", "svg".

RenditionFilters

RenditionFilters is the central class that computes which Wagtail renditions are needed for a given image. It is initialised with:

  • image – A Rectangle representing the original image dimensions.

  • original_format – The format of the original image file.

  • slots – A list of Rectangle objects representing the display slots the image must fit into.

  • image_formats – The output formats to generate (e.g. ["jpeg", "avif"]).

The class computes a fitting width for each slot by comparing the image’s aspect ratio with the slot’s aspect ratio, then generates RenditionFilter objects for each slot/format/pixel-density combination (1x, 2x, 3x). Renditions that would be nearly as large as the original are skipped. Gallery thumbnail slots can also include django-cast’s custom srgb Wagtail operation before any format-* conversion, so profiled thumbnail renditions use compact sRGB ICC profiles while modal/full-size renditions preserve their existing color handling.

Convenience constructors:

  • RenditionFilters.from_wagtail_image(image, slots, image_formats) – Creates filters from a Wagtail Image instance.

  • RenditionFilters.from_wagtail_image_with_type(image, image_type) – Creates filters using the configured slot dimensions for the given ImageType.

Key properties:

  • filter_strings – Returns a list of Wagtail filter spec strings (e.g. "width-300", "width-600|format-avif").

  • all_filters – Returns a flat list of all RenditionFilter objects.

ImageForSlot

ImageForSlot represents a single image sized to fit a particular slot. It carries the data needed to render a <picture> or <img> tag in a template:

  • width / height – The display dimensions.

  • sizes – A CSS sizes string (e.g. "740px").

  • src – A dict mapping each ImageFormat to its URL (used for the src attribute).

  • srcset – A dict mapping each ImageFormat to a srcset string (e.g. "image.avif 300w, image.avif 600w").

In templates, each image gets regular, thumbnail, or modal attributes (depending on context) that are ImageForSlot instances. Theme templates can access image.regular.srcset, image.regular.src, etc. to build responsive <picture> elements.

Rendition Workflow

The full rendering pipeline works as follows:

  1. When a post is requested, the repository pattern prefetches all images and their existing renditions in bulk.

  2. Each image block (CastImageChooserBlock or GalleryBlockWithLayout) creates a RenditionFilters instance for the image.

  3. The filter strings are matched against prefetched renditions. In the normal path all required renditions are already present. While the gallery thumbnail sRGB policy is being enabled or disabled, a missing requested thumbnail rendition temporarily uses its existing sRGB/non-sRGB counterpart instead of emitting an empty image URL.

  4. The get_image_for_slot() method produces an ImageForSlot object that is attached to the image and passed to the template context.

  5. Theme templates use the ImageForSlot attributes to render <picture> elements with appropriate <source> and <img> tags.

To create missing renditions in bulk (e.g. after changing slot dimensions, image formats, or gallery thumbnail color-profile policy), run this one-off management command after deploying the specification change:

python manage.py sync_renditions

The counterpart fallback keeps existing thumbnails visible until this command finishes; synchronization is still required to serve the newly configured renditions and clean up superseded thumbnail policy keys.

Publication consistency

Direct synchronize_post_media(post) calls update all built-in relationship sets in one transaction on the post’s write database. A failure leaves the previous media index intact. Body inspection and rendition preparation remain outside that relationship write boundary.

Canonical gallery creation locks existing effective image rows in primary-key order and rechecks the signature within the same transaction. Body inspection resolves all gallery sets as a batch, locking their complete union in order before creating any gallery. Code resolving several sets inside one outer transaction should use cast.models.gallery.get_or_create_galleries once, rather than accumulating locks through separate calls. PostgreSQL uses no-key update locks so unrelated rendition/relation FK inserts can proceed. Gallery locks last until an enclosing publication transaction finishes; rendition work may still run inside that enclosing transaction. On databases with row locks, concurrent creation for the same effective image set returns the same gallery, ignoring order, duplicate IDs and nonexistent IDs. SQLite does not offer row-level select_for_update serialization. Gallery membership stays mutable; there is no blanket unique constraint on its signature.

Raster GPS inspection is limited to 100 frames and 50 million decoded pixels in total across frames. Every permitted frame is inspected, including when an earlier frame already contains GPS. Inputs exceeding either budget are refused before storage; uninspected uploads are never accepted. The frame count is not queried before this bounded walk because some decoders calculate it by seeking through the entire animation.

These fixed limits also refuse GPS-free images: for example a 61 megapixel JPEG or a 101-frame animation. They are stricter than Wagtail’s single-image pixel limit and apply in addition to its upload-size checks.

The read-only report_image_gps command uses the same bounded inspection. Existing originals over the budget are reported separately as budget-exceeded images, with their IDs and storage names, rather than as unreadable. It leaves every original untouched and exits nonzero because GPS status for those originals is unknown; it does not scan them without a bound.