django-imagekit

6.1.0 · active · verified Wed Apr 15

Django-imagekit is a Django application for automated image processing on models. It allows developers to define "specs" for variations of uploaded images, such as thumbnails or black-and-white versions, which are generated on demand. The library maintains a moderate release cadence, often aligning with new Django and Python version releases to ensure compatibility and leverage modern features.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to integrate `django-imagekit` into your Django models. It showcases two primary field types: `ImageSpecField` for on-the-fly image generation from a source field, and `ProcessedImageField` for directly saving a processed image to a new field. Define your desired processors (e.g., resizing, cropping) and format options directly in your model fields. Ensure 'imagekit' is added to your Django project's `INSTALLED_APPS`.

from django.db import models
from imagekit.models import ImageSpecField, ProcessedImageField
from imagekit.processors import ResizeToFill
from django.conf import settings

# NOTE: This code snippet demonstrates model field definitions.
# For a runnable example, you need a full Django project setup
# including settings.py (e.g., MEDIA_ROOT, MEDIA_URL, INSTALLED_APPS).
# In settings.py, ensure 'imagekit' is in INSTALLED_APPS.

# Example Django Model
class Product(models.Model):
    name = models.CharField(max_length=255)
    # Original image field where users upload their files
    original_photo = models.ImageField(upload_to='products', blank=True, null=True)
    
    # ImageSpecField for an automatically generated thumbnail
    # This field does not create a database column, but provides an interface
    # to a dynamically generated image based on 'original_photo'.
    thumbnail = ImageSpecField(
        source='original_photo',
        processors=[ResizeToFill(100, 100)],
        format='JPEG',
        options={'quality': 75}
    )

    # ProcessedImageField for a product detail image, directly saved.
    # This field creates a database column and stores the path to the
    # processed image file. This is useful if you want to save a processed
    # version directly or don't need the original.
    detail_image = ProcessedImageField(
        upload_to='product_details',
        processors=[ResizeToFill(800, 600)],
        format='PNG',
        options={'quality': 85},
        blank=True, 
        null=True
    )

    def __str__(self):
        return self.name

# To use:
# product = Product.objects.create(name='Example', original_photo='path/to/image.jpg')
# # Accessing .url will trigger image generation (for ImageSpecField) or retrieve path (for ProcessedImageField)
# print(product.thumbnail.url)
# print(product.detail_image.url)

view raw JSON →