以编程方式在Wagtail中添加StreamBlock子项

时间:2017-10-17 17:29:06

标签: wagtail wagtail-streamfield

我在下面有以下StructBlock和StreamBlock:

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

class AccordionRepeaterBlock(StreamBlock):
    accordion_item = AccordionItemBlock()

我需要以编程方式将它和多个“item”CharBlocks添加到此页面:

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'之后放入第二个元组值,我都会收到错误。任何想法如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

找到解决方案!您必须使子块阻止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()