如何以编程方式将内容添加到Wagtail StreamField?

sed*_*nym 12 django wagtail

我正在从旧网站进行迁移,我需要以编程方式将原始html添加到StreamFieldWagtail页面上.我该怎么做?

sed*_*nym 18

最简单的方法是确保RawHTMLBlock已启用StreamField,然后将其插入.向该字段添加内容的过程如下:

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()
Run Code Online (Sandbox Code Playgroud)

您可以使用此方法添加其他类型的块StreamField- 只需确保创建具有适当块类型的字典列表,将其转换为json,然后保存.

  • 请注意,至少从Wagtail 1.5开始,您不需要使用从字典数组创建的JSON字符串.您可以直接使用元组数组,如下所示:`my_page.body = [('raw_html',original_html)]` (2认同)