创建新页面时 wagtail 的 StreamField 的默认块

Default blocks for wagtail's StreamField when a new Page is created

有没有办法在创建新页面时使用具有默认块的 StreamField 创建页面模型?

例如我有这个自定义页面:

class CustomPage(Page):
    body = StreamField([("text", TextBlock())])

而且当我打开“添加新页面”视图时,我总是希望在正文中有一个带有默认文本的文本块。

以及如何使用像 ItemList 这样更复杂的块来做到这一点?

class Item(StructBlock):
    text = CharBlock()
    image = ImageChooserBlock()

class ItemList(StructBlock):
    items = StreamBlock([("item", Item()),])

StreamField 字段定义接受一个 default 参数,该参数由 (block_name, value) 元组列表组成。因此,对于初始状态为单个 'text' 块的 StreamField,您可以编写:

class CustomPage(Page):
    body = StreamField(
        [("text", TextBlock())],
        default=[("text", "hello world!")]
    )

同样的事情应该适用于更复杂的块类型,但是在指定块值时,您需要注意匹配嵌套中每个点的预期值类型:一个 StreamBlock 对应于一个列表元组如上所述,并且 StructBlock 对应于 dict 值,因此第二项中的 default 值必须是:

  • ('item_list',值)元组的列表,其中值是:
  • 带有 'items' 键的字典,其值为:
  • ('item',值)元组的列表,其中值是:
  • 由'text'(值为字符串)和'image'(值为图片ID)组成的字典

(或者类似的东西,无论如何!)