1

I've added a caption field to a custom image model with the help of this and this. How do I show that caption field in images that are in a richtext field?

Mark Horgan
  • 3,243
  • 4
  • 27
  • 28

1 Answers1

2

This is possible by defining a custom image format - in this case, you'd need to create a subclass of Format that overrides the image_to_html method. There's an example of this here: https://github.com/torchbox/verdant-rca/blob/d9ede994dbd1ef68eaa159ec930fd89a351c1329/django-verdant/rca/image_formats.py#L4-L25

However, I'd strongly recommend using StreamField for this kind of mixed content instead. Images with captions are at the upper end of what's practical within a rich text field, and the behaviour can be a bit glitchy (for example, it's difficult to insert text after an image that's at the end of the field, or before an image at the beginning). It's also not great for separation of content and presentation. With StreamField, your text and image are represented as distinct objects in the admin, and within the template you have full control over the HTML used for them.

gasman
  • 23,691
  • 1
  • 38
  • 56
  • Here's an updated link to docs on custom image format: http://docs.wagtail.io/en/v2.7/advanced_topics/customisation/page_editing_interface.html#image-formats-in-the-rich-text-editor – Mark Horgan Jan 02 '20 at 09:26
  • Updated link to docs from 2022: https://docs.wagtail.org/en/stable/advanced_topics/images/changing_rich_text_representation.html – yellow-saint Nov 02 '22 at 07:20