custom_image_model.rst 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. .. _custom_image_model:
  2. ===================
  3. Custom image models
  4. ===================
  5. The ``Image`` model can be customised, allowing additional fields to be added
  6. to images.
  7. To do this, you need to add two models to your project:
  8. - The image model itself that inherits from ``wagtail.images.models.AbstractImage``. This is where you would add your additional fields
  9. - The renditions model that inherits from ``wagtail.images.models.AbstractRendition``. This is used to store renditions for the new model.
  10. Here's an example:
  11. .. code-block:: python
  12. # models.py
  13. from django.db import models
  14. from wagtail.images.models import Image, AbstractImage, AbstractRendition
  15. class CustomImage(AbstractImage):
  16. # Add any extra fields to image here
  17. # eg. To add a caption field:
  18. # caption = models.CharField(max_length=255, blank=True)
  19. admin_form_fields = Image.admin_form_fields + (
  20. # Then add the field names here to make them appear in the form:
  21. # 'caption',
  22. )
  23. class CustomRendition(AbstractRendition):
  24. image = models.ForeignKey(CustomImage, on_delete=models.CASCADE, related_name='renditions')
  25. class Meta:
  26. unique_together = (
  27. ('image', 'filter_spec', 'focal_point_key'),
  28. )
  29. Then set the ``WAGTAILIMAGES_IMAGE_MODEL`` setting to point to it:
  30. .. code-block:: python
  31. WAGTAILIMAGES_IMAGE_MODEL = 'images.CustomImage'
  32. .. topic:: Migrating from the builtin image model
  33. When changing an existing site to use a custom image model, no images will
  34. be copied to the new model automatically. Copying old images to the new
  35. model would need to be done manually with a
  36. :ref:`data migration <django:data-migrations>`.
  37. Any templates that reference the builtin image model will still continue to
  38. work as before but would need to be updated in order to see any new images.
  39. .. _custom_image_model_referring_to_image_model:
  40. Referring to the image model
  41. ============================
  42. .. module:: wagtail.images
  43. .. autofunction:: get_image_model
  44. .. autofunction:: get_image_model_string