python - 在继承类中扩展 wagtail Streamfields

标签 python django wagtail

我有一个抽象类,其中包含 StreamField。我还有一个继承自 BasePage 的类 CustomPage。我希望 CustomPage 向内容添加新的 StructBlock。我该怎么做?

class BasePage(Page):
    content = StreamField([
        ('ad', ...),
        ('text', ...),
        ('img', ...),
    ])
    content_panels = Page.content_panels + [
        StreamFieldPanel('content'),
    ]

    class Meta:
        abstract = True

class CustomPage(BasePage):
    # add ('custom_block', ...) to content streamfield.

最佳答案

StreamField 定义不能直接以这种方式“扩展”,但通过一些重新洗牌,您可以定义一个重新使用相同 block 列表的新 StreamField:

COMMON_BLOCKS = [
    ('ad', ...),
    ('text', ...),
    ('img', ...),
]

class BasePage(Page):
    content = StreamField(COMMON_BLOCKS)
    ...

class CustomPage(BasePage):
    content = StreamField(COMMON_BLOCKS + [
        ('custom_block', ...),
    ])

或者在 StreamBlock 上使用继承(您可能认为这比连接列表更简洁:

class CommonStreamBlock(StreamBlock):
    ad = ...
    text = ...
    img = ...

class CustomStreamBlock(CommonStreamBlock):
    custom_block = ...

class BasePage(Page):
    content = StreamField(CommonStreamBlock())
    ...

class CustomPage(BasePage):
    content = StreamField(CustomStreamBlock())

另外,请注意这是 only possible since Django 1.10 - 旧版本的 Django 不允许覆盖抽象父类(super class)的字段。

关于python - 在继承类中扩展 wagtail Streamfields,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41538129/

相关文章:

python - 遍历嵌套列表并对每个元素进行操作

django - Django 应用程序中的 "' 标记 ' is not a registered tag library. Must be one of"

python - 如何从静态标签 wagtail 2.5 中的变量提供 webp

python - 在azure应用程序服务上使用python 3.6 - 尽管它作为扩展安装,但不起作用

python - 如何检查集合中是否已存在列表的 "unsorted version"?

python - 正则表达式命名组以开头但不以结尾

python - 是否有基于浏览器的 Python IDE,例如 R 的 RStudio 服务器?

sql - 引用 URL 中的对象 - 您使用主键还是最佳实践是什么?

python - Django 管理员身份验证如何工作?

python - Django/Wagtail 一些图片上传错误500