How can I programmatically add content to a Wagtail StreamField?
Asked Answered
K

1

15

I'm doing a migration from an old site, and I need to programmatically add raw html to a StreamField on a Wagtail page. How do I do it?

Knighton answered 10/12, 2015 at 11:34 Comment(0)
K
24

The easiest way to do this is to make sure that RawHTMLBlock is enabled on your StreamField, and then insert it there. The process for adding content to the field is as follows:

import json

original_html = '<p>Hello, world!</p>'

# First, convert the html to json, with the appropriate block type
raw_json = json.dumps([{'type': 'raw_html', 'value': original_html}])

# Load Wagtail page
my_page = Page.objects.get(id=1)
# Assuming the stream field is called 'body',
# add the json string to the field
my_page.body = raw_json
my_page.save()

You can use this approach to add other kinds of blocks to the StreamField - just make sure you create a list of dictionaries with the appropriate block type, convert it to json, and save.

Knighton answered 10/12, 2015 at 11:34 Comment(1)
Note that as of at least Wagtail 1.5, you need not use a JSON string created from an array of dictionaries. You can instead use an array of tuples directly, like so: my_page.body = [('raw_html', original_html)]Cavesson

© 2022 - 2024 — McMap. All rights reserved.