Custom image models¶
The Image
model can be customized, allowing additional fields to be added
to images.
To do this, you need to add two models to your project:
The image model itself that inherits from
wagtail.images.models.AbstractImage
. This is where you would add your additional fieldsThe renditions model that inherits from
wagtail.images.models.AbstractRendition
. This is used to store renditions for the new model.
Here’s an example:
# models.py
from django.db import models
from wagtail.images.models import Image, AbstractImage, AbstractRendition
class CustomImage(AbstractImage):
# Add any extra fields to image here
# To add a caption field:
# caption = models.CharField(max_length=255, blank=True)
admin_form_fields = Image.admin_form_fields + (
# Then add the field names here to make them appear in the form:
# 'caption',
)
class CustomRendition(AbstractRendition):
image = models.ForeignKey(CustomImage, on_delete=models.CASCADE, related_name='renditions')
class Meta:
unique_together = (
('image', 'filter_spec', 'focal_point_key'),
)
Then set the WAGTAILIMAGES_IMAGE_MODEL
setting to point to it:
WAGTAILIMAGES_IMAGE_MODEL = 'images.CustomImage'
Migrating from the builtin image model¶
When changing an existing site to use a custom image model, no images will be copied to the new model automatically. Copying old images to the new model would need to be done manually with a data migration.
Any templates that reference the builtin image model will still continue to work as before but would need to be updated in order to see any new images.
Referring to the image model¶
- wagtail.images.get_image_model()¶
Get the image model from the
WAGTAILIMAGES_IMAGE_MODEL
setting. Useful for developers making Wagtail plugins that need the image model. Defaults to the standardwagtail.images.models.Image
model if no custom model is defined.
- wagtail.images.get_image_model_string()¶
Get the dotted
app.Model
name for the image model as a string. Useful for developers making Wagtail plugins that need to refer to the image model, such as in foreign keys, but the model itself is not required.
Overriding the upload location¶
The following methods can be overridden on your custom Image
or Rendition
models to customize how the original and rendition image files get stored.
- class wagtail.images.models.AbstractImage¶
- get_upload_to(filename)¶
Generates a file path in the “original_images” folder. Ensuring ASCII characters and limiting length to prevent filesystem issues during uploads.
- class wagtail.images.models.AbstractRendition¶
- get_upload_to(filename)¶
Generates a file path within the “images” folder by combining the folder name and the validated filename.
Refer to the Django FileField.upload_to
function to further understand how the function works.