在 Wagtail 中以编程方式添加 StreamBlock 子项 [英] Add StreamBlock child items programmatically in Wagtail

查看:22
本文介绍了在 Wagtail 中以编程方式添加 StreamBlock 子项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面有以下 StructBlock 和 StreamBlock:

I have the following StructBlock and StreamBlock below:

class AccordionItemBlock(StructBlock):
    title = CharBlock()
    text = RichTextBlock()

class AccordionRepeaterBlock(StreamBlock):
    accordion_item = AccordionItemBlock()

我需要以编程方式将它和多个项目"CharBlock 添加到此页面:

I need to programmatically add it and multiple "item" CharBlocks to this page:

class BasicPage(Page):
    body = StreamField([
        ('accordion_repeater_block', AccordionRepeaterBlock()),
    ], null=True)

这就是我接近它的方式

page.body = [
    (
        'accordion_repeater_block',
        {
            'accordion_item',
            {
                'title': 'Title goes here',
                'text': RichText('Testing!'),
            }
        }
    )
]
provider.save()

无论我在 'accordion_repeater_block' 之后的第二个元组值中输入什么,我都会收到错误.任何想法如何解决这个问题?

I get errors no matter what I put in the second tuple value after 'accordion_repeater_block'. Any ideas how to solve this?

推荐答案

找到解决方案!您必须使子块成为 StreamValue.StreamChild 的实例:

Found the solution! You have to make the child blocks an instance of StreamValue.StreamChild:

from wagtail.wagtailcore.blocks.stream_block import StreamValue

page.body = [
    ('accordion_repeater_block',
        [
            StreamValue.StreamChild(
                id=None,
                block=AccordionItemBlock(),
                value={
                        'title': 'Title goes here',
                        'text': RichText('Testing!'),
                }
            ),
        ]
    )
]
page.save()

这篇关于在 Wagtail 中以编程方式添加 StreamBlock 子项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆