2022-04-16 03:14:06 +02:00
(custom_image_model)=
# Custom image models
2024-01-29 14:23:55 +01:00
The `Image` model can be customized, allowing additional fields to be added
2022-04-16 03:14:06 +02:00
to images.
To do this, you need to add two models to your project:
2022-05-26 15:24:47 +02:00
- The image model itself that inherits from `wagtail.images.models.AbstractImage` . This is where you would add your additional fields
- The renditions model that inherits from `wagtail.images.models.AbstractRendition` . This is used to store renditions for the new model.
2022-04-16 03:14:06 +02:00
Here's an example:
```python
# 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
2022-07-18 14:00:02 +02:00
# To add a caption field:
2022-04-16 03:14:06 +02:00
# 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:
```python
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
{ref}`data migration < django:data-migrations > `.
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.
(custom_image_model_referring_to_image_model)=
## Referring to the image model
```{eval-rst}
.. module:: wagtail.images
.. autofunction:: get_image_model
.. autofunction:: get_image_model_string
2022-05-26 15:24:47 +02:00
```
2024-01-22 08:06:25 +01:00
(custom_image_model_upload_location)=
## 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.
```{eval-rst}
.. automodule:: wagtail.images.models
2024-06-07 15:20:11 +02:00
:no-index:
2024-01-22 08:06:25 +01:00
.. class:: AbstractImage
2024-07-22 17:21:26 +02:00
:no-index-entry:
2024-01-22 08:06:25 +01:00
.. automethod:: get_upload_to
.. class:: AbstractRendition
2024-07-22 17:21:26 +02:00
:no-index-entry:
2024-01-22 08:06:25 +01:00
.. automethod:: get_upload_to
```
2024-11-01 18:30:48 +01:00
Refer to the Django [`FileField.upload_to` ](django.db.models.FileField.upload_to ) function to further understand how the function works.