Mark Horgan
Mark Horgan

Reputation: 3313

Customizing images in richtext fields

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?

Upvotes: 1

Views: 1007

Answers (1)

gasman
gasman

Reputation: 25227

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.

Upvotes: 2

Related Questions