在 Wagtail 中以编程方式添加 StreamBlock 子项
Add StreamBlock child items programmatically in Wagtail
我有下面的 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' 之后的第二个元组值中输入什么,我都会出错。有什么解决办法吗?
找到解决方案!您必须使子块成为 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()
我有下面的 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' 之后的第二个元组值中输入什么,我都会出错。有什么解决办法吗?
找到解决方案!您必须使子块成为 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()