Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I programmatically add content to a Wagtail StreamField?

Tags:

django

wagtail

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?

like image 431
seddonym Avatar asked Dec 10 '15 11:12

seddonym


People also ask

What is StreamField in wagtail?

The StreamField is a list which contains the value and type of the sub-blocks (we will see it in a bit). You can use the built-in block shipped with Wagtail or you can create your custom block. Some block can also contains sub-block so you can use it to create a complex nested data structure, which is powerful .

What is orderable wagtail?

Orderables let you add movable content to your page without needing a StreamField. In this video, we'll create a Bootstrap 4 Image Gallery on our Home Page model using an Orderable.


1 Answers

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.

like image 53
seddonym Avatar answered Sep 17 '22 00:09

seddonym