custom_image_model.rst 2.1 KB

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