如何创建 Page 并以编程方式设置其 StreamField 值?

How can I create Page and set its StreamField value programmatically?

我想在 wagtail 中以编程方式创建一个 BlogPage 并设置其 StreamField 值。我可以设置 heading 字段。但是当我尝试设置 paragraph 字段时,我得到 AttributeError: 'unicode' object has no attribute 'source'。我也想配个图

这是我的 BlogPage 模型。

models.py

class BlogPage(Page):
template = 'wagtail/test_page.html'
author = models.CharField(max_length=255)
date = models.DateField("Post date")
body = StreamField([
    ('heading', blocks.CharBlock(classname="full title")),
    ('paragraph', blocks.RichTextBlock()),
    ('image', ImageChooserBlock()),
])

content_panels = Page.content_panels + [
    FieldPanel('author'),
    FieldPanel('date'),
    StreamFieldPanel('body'),
]

这是我的代码,用于通过 运行 此脚本创建页面。

create_page.py

new_image_page = BlogPage(
    title='Blog',
    slug='michael',
    author='michael',
    date='2017-12-13',
    body=[('heading','New Heading'), ('heading','New Heading 23232'), ('paragraph','My Paragraph')]
)

directory_page = Page.objects.get(slug='home')
directory_page.add_child(instance=new_image_page)
revision = new_image_page.save_revision()
revision.publish()
new_image_page.save()

以编程方式添加 StreamField 的数据时,最好将数据作为原始 json 字符串输入。数据将是一个字典数组,其中每个字典包含一个 type 和一个 value.

这应该可以解决您 运行 遇到的任何字符串转换问题。

import json

new_image_page = BlogPage(
    title='Blog',
    slug='michael',
    author='michael',
    date='2017-12-13',
    body=json.dumps([
      {'type':'heading', 'value': 'New Heading'},
      {'type':'heading', 'value': 'New Heading 23232'},
      {'type':'paragraph', 'value': '<strong>My Paragraph</strong>'},
    ])
)

要添加图像,您将执行类似的操作,其中值是图像的 pk (ID)。

{'type': 'image', 'value': my_image.pk},

起初我使用 Wagtail 管理界面创建了一个 BlogPage,并手动将其设置为 StreamField(heading etc.)。我使用 python shell 中的 __dict__ 检查了新创建的 BlogPage 对象的属性。然后我在过滤 body StreamFieldPanel 后得到了这些结果 'stream_data': [{u'type': u'heading', u'id': u'0ebe1070-d167-48a0-9c57-70e4ad068ae5', u'value': u'New Heading'}]。 在看到 stream_data 的结构并从 LB Ben Johnston 的回答中得到使用 json.dumps() 的建议后,我得到了我的解决方案。

这是我的解决方案。

import json

new_image_page = BlogPage(
   title='Blog',
   slug='michael',
   author='michael',
   date='2017-12-13',
   body = json.dumps([
       {u'type': u'heading', u'value': u'New Heading 23232'},
       {u'type': u'heading', u'value': u'New Heading 23232'},
       {u'type': u'paragraph', u'value': u'New Paragraph'},
       ])
)