如何以编程方式创建包含 StreamField 的 Wagtail StructBlock?

问题描述 投票:0回答:0

我已经定义了一个自定义的

StructBlock
和一个
StreamField
允许
StructBlock
实例,如下所示:

class NavigationPageChooserBlock(wagtail_blocks.StructBlock):
    title = wagtail_blocks.CharBlock()
    page = wagtail_blocks.PageChooserBlock()


class NavigationDropdownMenuBlock(wagtail_blocks.StructBlock):
    title = wagtail_blocks.CharBlock()
    menu_items = wagtail_blocks.StreamBlock(
        [
            ("page", NavigationPageChooserBlock()),
        ]
    )

对于完整的上下文,这些块用作自定义

NavigationMenuSetting
的一部分,我需要在来自Drupal站点的内容导入器中使用它。

@register_setting
class NavigationMenuSetting(BaseSiteSetting):
    menu_items = StreamField(
        [
            ("drop_down", NavigationDropdownMenuBlock()),
        ],
        use_json_field=True,
    )

我在尝试弄清楚如何在 Python 代码中创建一个带有子

NavigationDropdownMenuBlock
menu_items
实例时遇到了很多困难。我试过以下方法,但出现错误。

/wagtail/blocks/stream_block.py", line 290, in get_prep_value
    return value.get_prep_value()
           ^^^^^^^^^^^^^^^^^^^^
AttributeError: 'list' object has no attribute 'get_prep_value'

这是我的进口商代码:

# example_page is created previously

# NavigationDropdownMenuBlock (StructBlock)
example_dropdown = {
    "title": "Dropdown Menu",
    # StreamBlock
    "menu_items": [
        (
            "page",
            # NavigationPageChooserBlock (StructBlock)
            {
                "title": "Example Page Link",
                "page": example_page,
            },
        ),
    ],
}

navigation_items = [
    ("drop_down", example_dropdown),
]
navigation_menu = NavigationMenuSetting(
    menu_items=navigation_items,
    site_id=1,
)

navigation_menu.save()

如何更改我的导入脚本以正确创建

example_dropdown
NavigationMenuSetting.menu_items
项目?

wagtail wagtail-streamfield wagtail-blocks
© www.soinside.com 2019 - 2024. All rights reserved.