Skip to content

Instantly share code, notes, and snippets.

@MattSegal
Created August 8, 2018 22:55
Show Gist options
  • Save MattSegal/342b33b896a34326857672f2e9693a14 to your computer and use it in GitHub Desktop.
Save MattSegal/342b33b896a34326857672f2e9693a14 to your computer and use it in GitHub Desktop.
Wagtail body image lookup
from bs4 import BeautifulSoup
from wagtail.core.fields import RichTextField
from wagtail.core.models import Page
class BlogPost(Page):
body = RichTextField()
images = models.ManyToManyField('wagtailimages.Image')
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
self.update_body_images()
def update_body_images(self):
parsed_body = BeautifulSoup(self.body, 'html.parser')
image_ids_unique = set()
for image in parsed_body.find_all('embed', embedtype='image'):
image_pk_str = image.get('id', '')
image_ids_unique.add(int(image_pk_str))
if not self.has_unpublished_changes:
# Store unique image ids on the images field so that we can look them up
self.images.set(image_ids_unique)
@property
def body_image_urls(self):
rendition_filter = 'original' # Maybe use something different
return [img.get_rendition(rendition_filter).url for img in self.images.all()]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment