Programmatically adding images to Wagtail

Here’s just a little code snippet to download an image using requests and upload that same image into Wagtail where it can be used in templates.

import requests
from wagtail.images.models import Image
from io import BytesIO
from django.core.files.images import ImageFile


http_res = requests.get(image_url)
title = 'my_image_file.jpg'
image_file = ImageFile(BytesIO(http_res.content), name=title)
image = Image(title=title, image_file)
image.save()

In order to insert images into a RichTextField, you’ll need to convert them into an embed. If you’ve got existing HTML with image tags, you can do this with BeautifulSoup. Assuming you’ve just kept the same file paths as the title:

from bs4 import BeautifulSoup

def replace_images_with_embeds(body):
    soup = BeautifulSoup(body, 'lxml')
    for img in soup.find_all("img"):
        print('found image:', img['src'])
        filename = re.sub(r'http://.+?/', '', img['src'])
        image = Image.objects.get(title=filename)
        embed = soup.new_tag('embed')
        embed['format'] = 'fullwidth'
        embed['id'] = image.pk
        embed['embedtype'] = 'image'
        embed['alt'] = filename
        img.parent.insert_after(embed)
        img.decompose() # remove the unused img

Leave a Reply

Your email address will not be published. Required fields are marked *