This is a maintained fork of codingjoe/django-stdimage with compatibility fixes for Django 5+, WebP output support, and other improvements. Source: github.com/igorkhaylov/django-stdimage
Note: If you are starting a new project, consider django-pictures — a modern alternative with responsive image support.
This is a drop-in replacement for the Django ImageField that provides a standardized way to handle image uploads. It is designed to be as easy to use as possible, and to provide a consistent interface for all image fields. It allows images to be presented in various size variants (eg:thumbnails, mid, and hi-res versions) and it provides a way to handle images that are too large with validators.
Django Standardized Image Field implements the following features:
- Django-Storages compatible (eg: S3, Azure, Google Cloud Storage, etc)
- Resizes images to different sizes
- Access thumbnails on model level, no template tags required
- Preserves original images
- Can be rendered asynchronously (ie as a Celery job)
- Restricts acceptable image dimensions
- Renames a file to a standardized name format (using a callable
upload_tofunction, see below)
This fork is not published on PyPI. Install directly from GitHub.
pip install git+https://github.com/igorkhaylov/django-stdimage.git@v1.0.2With optional extras:
# With progressbar support for the rendervariations command
pip install "git+https://github.com/igorkhaylov/django-stdimage.git@v1.0.2#egg=django-stdimage[progressbar]"
# With Django REST Framework serializer
pip install "git+https://github.com/igorkhaylov/django-stdimage.git@v1.0.2#egg=django-stdimage[drf]"poetry add git+https://github.com/igorkhaylov/django-stdimage.git@v1.0.2Or add manually to pyproject.toml:
[tool.poetry.dependencies]
django-stdimage = { git = "https://github.com/igorkhaylov/django-stdimage.git", tag = "v1.0.2" }uv add git+https://github.com/igorkhaylov/django-stdimage.git@v1.0.2pdm add git+https://github.com/igorkhaylov/django-stdimage.git@v1.0.2pipenv install git+https://github.com/igorkhaylov/django-stdimage.git@v1.0.2#egg=django-stdimagedjango-stdimage @ git+https://github.com/igorkhaylov/django-stdimage.git@v1.0.2
After installation, add 'stdimage' to INSTALLED_APPS in your settings.py:
INSTALLED_APPS = [
...
'stdimage',
]StdImageField works just like Django's own
ImageField
except that it automatically generates size variations of uploaded images.
The simplest usage requires no configuration — default variations are included out of the box:
from django.db import models
from stdimage import StdImageField
class MyModel(models.Model):
image = StdImageField(upload_to='path/to/img')This will automatically create the following variations for every uploaded image:
| Variation | Width | Height | Crop |
|---|---|---|---|
thumbnail |
100px | 100px | Yes |
small |
400px | auto | No |
medium |
800px | auto | No |
large |
1920px | auto | No |
All variations are saved in WebP format with quality 85.
To use a different default set for every StdImageField that does not declare its own
variations, define STDIMAGE_DEFAULT_VARIATIONS in your Django settings. It has the
same shape as the variations argument (dicts or (width, height, crop) tuples):
# settings.py
STDIMAGE_DEFAULT_VARIATIONS = {
"thumbnail": {"width": 150, "height": 150, "crop": True},
"card": {"width": 600, "height": None},
}Resolution order for a field declared without variations:
variations=...passed to the field (always wins;variations={}means none);settings.STDIMAGE_DEFAULT_VARIATIONS, when the setting is defined ({}disables default variations project-wide);- the built-in defaults from the table above, when the setting is not defined.
The resolved set is read when the field is created (model import time) and, like
explicit variations, it is written into migrations — changing the setting later is an
AlterField for every affected field (makemigrations), and existing files need
rendervariations to produce the new sizes.
Access variations on the model instance:
obj = MyModel.objects.get(pk=1)
obj.image.url # original image
obj.image.thumbnail.url # 100x100 cropped thumbnail
obj.image.small.url # 400px wide
obj.image.medium.url # 800px wide
obj.image.large.url # 1920px wideIn templates:
<img src="{{ object.image.thumbnail.url }}" alt="">
<img src="{{ object.image.medium.url }}" alt="">The package includes a serializer for Django REST Framework. Install with the drf extra (see Installation above).
from rest_framework import serializers
from stdimage.serializers import StdImageSerializer
from .models import MyModel
class MyModelSerializer(serializers.ModelSerializer):
image = StdImageSerializer()
class Meta:
model = MyModel
fields = '__all__'The serializer returns a dictionary with URLs for the original image and each variation:
{
"image": {
"original": "/media/path/to/img/image.jpg",
"thumbnail": "/media/path/to/img/image.thumbnail.webp",
"small": "/media/path/to/img/image.small.webp",
"medium": "/media/path/to/img/image.medium.webp",
"large": "/media/path/to/img/image.large.webp"
}
}If the image field is empty, the serializer returns null.
You can also define your own variations instead of using the defaults. Variations are specified within a dictionary. The key will be the attribute referencing the resized image. A variation can be defined both as a tuple or a dictionary.
Example:
from django.db import models
from stdimage import StdImageField, JPEGField
class MyModel(models.Model):
# works just like django's ImageField
image = StdImageField(upload_to='path/to/img')
# creates a thumbnail resized to maximum size to fit a 100x75 area
image = StdImageField(upload_to='path/to/img',
variations={'thumbnail': {'width': 100, 'height': 75}})
# is the same as dictionary-style call
image = StdImageField(upload_to='path/to/img', variations={'thumbnail': (100, 75)})
# JPEGField variations are converted to JPEGs.
jpeg = JPEGField(
upload_to='path/to/img',
variations={'full': (None, None), 'thumbnail': (100, 75)},
)
# creates a thumbnail resized to 100x100 croping if necessary
image = StdImageField(upload_to='path/to/img', variations={
'thumbnail': {"width": 100, "height": 100, "crop": True}
})
## Full ammo here. Please note all the definitions below are equal
image = StdImageField(upload_to='path/to/img', blank=True, variations={
'large': (600, 400),
'thumbnail': (100, 100, True),
'medium': (300, 200),
}, delete_orphans=True)JPEGField is identical to StdImageField but converts all images to JPEG format regardless of the original file type.
You can use a function for the upload_to argument. Using [Django Dynamic Filenames][dynamic_filenames].[dynamic_filenames]: https://github.com/codingjoe/django-dynamic-filenames
This allows images to be given unique paths and filenames based on the model instance.
Example
from django.db import models
from stdimage import StdImageField
from dynamic_filenames import FilePattern
upload_to_pattern = FilePattern(
filename_pattern='my_model/{app_label:.25}/{model_name:.30}/{uuid:base32}{ext}',
)
class MyModel(models.Model):
# works just like django's ImageField
image = StdImageField(upload_to=upload_to_pattern)The StdImageField doesn't implement any size validation out-of-the-box.
However, Validation can be specified using the validator attribute
and using a set of validators shipped with this package.
Validators can be used for both Forms and Models.
Example
from django.db import models
from stdimage.validators import MinSizeValidator, MaxSizeValidator
from stdimage.models import StdImageField
class MyClass(models.Model):
image1 = StdImageField(validators=[MinSizeValidator(800, 600)])
image2 = StdImageField(validators=[MaxSizeValidator(1028, 768)])CAUTION: The MaxSizeValidator should be used with caution. As storage isn't expensive, you shouldn't restrict upload dimensions. If you seek prevent users form overflowing your memory you should restrict the HTTP upload body size.
Django dropped support for automated deletions in version 1.3.
Since version 5, this package supports a delete_orphans argument. It will delete
orphaned files, should a file be deleted or replaced via a Django form and the object with
the StdImageField be deleted. It will not delete files if the field value is changed or
reassigned programatically. In these rare cases, you will need to handle proper deletion
yourself.
from django.db import models
from stdimage.models import StdImageField
class MyModel(models.Model):
image = StdImageField(
upload_to='path/to/files',
variations={'thumbnail': (100, 75)},
delete_orphans=True,
blank=True,
)Tools like celery allow to execute time-consuming tasks outside of the request. If you don't want to wait for your variations to be rendered in request, StdImage provides you the option to pass an async keyword and a 'render_variations' function that triggers the async task. Note that the callback is not transaction save, but the file variations will be present. The example below is based on celery.
tasks.py:
from django.apps import apps
from celery import shared_task
from stdimage.utils import render_variations
@shared_task
def process_photo_image(file_name, variations, storage):
render_variations(file_name, variations, replace=True, storage=storage)
obj = apps.get_model('myapp', 'Photo').objects.get(image=file_name)
obj.processed = True
obj.save()models.py:
from django.db import models
from stdimage.models import StdImageField
from .tasks import process_photo_image
def image_processor(file_name, variations, storage):
process_photo_image.delay(file_name, variations, storage)
return False # prevent default rendering
class AsyncImageModel(models.Model):
image = StdImageField(
# above task definition can only handle one model object per image filename
upload_to='path/to/file/', # or use a function
render_variations=image_processor # pass boolean or callable
)
processed = models.BooleanField(default=False) # flag that could be used for view querysetsYou might have added or changed variations to an existing field. That means you will need to render new variations. This can be accomplished using a management command.
python manage.py rendervariations 'app_name.model_name.field_name' [--replace] [-i/--ignore-missing]The replace option will replace all existing files.
The ignore-missing option will suspend 'missing source file' errors and keep
rendering variations for other files. Otherwise, the command will stop on first missing file.