Using a Custom Image Model in Wagtail CRX¶
Added in version 0.19: Added support for custom image models. You must be on Wagtail CRX version 0.19 or higher in order to follow this guide.
Using a custom image model is a very similar process to using a custom user model in Django — it is easy to do when starting a new project but extremely difficult to do mid-project. This guide will cover starting a new project using a custom image model. To switch to a custom image model mid-project, see Convert Existing Site to Use a Custom Image Model.
Before starting this guide, it is important that you are starting with a fresh empty database and have never run coderedcms migrations!
Step 1: Create a custom image model in a new app¶
It is imperative that the custom image model lives in a Django app which does
not rely on or import coderedcms
. It is recommended to create a separate
“pure” app to contain custom image and document models for your site. Failure
to separate the custom image model will create a circular dependency issue in
migrations.
Create an empty Django app, ours will be named mediamodels
:
$ django-admin startapp mediamodels
In mediamodels/models.py
, add your custom image model code, following the
Wagtail custom image sample code:
# 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
# eg. 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'),
)
Step 2: Make migrations¶
Before switching your project to the new custom model, first make a migration for this model. If your custom image model already exists and has already been migrated, you can skip this step.
$ python manage.py makemigrations mediamodels
Step 3: Switch to the new image model¶
In your Django settings file, (probably under settings/base.py
) set the
WAGTAILIMAGES_IMAGE_MODEL
setting to point to it:
WAGTAILIMAGES_IMAGE_MODEL = "mediamodels.CustomImage"
Step 4: Migrate Wagtail CRX¶
Now you may run all migrations which will properly wire everything up to use your custom image model.
$ python manage.py migrate