使用或重用 Wagtail StreamField 块作为其他模型中的 Fields

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

我有一个 Wagtail 项目,有两个不同的

Page
模型,它们使用相同的画廊块,但方式不同。在一个模型中,我想在其他自由形式块的列表中使用图库;但在另一种模型中,只有一个画廊出现在页面上的特定位置。画廊非常复杂,有很多像
autoadvance
这样的选项,我不想在模型之间重复,而且不容易转移到 mixin 中。我可以通过向严格模型添加额外的
gallery
StreamField 来完成我想要的,如下所示:
content_panel
等省略)

# models.py
from wagtail.models import Page
from wagtail.core.fields import RichTextField, StreamField
from wagtail.images.blocks import ImageChooserBlock
from wagtail.core.blocks import (
    RichTextBlock, 
    StructBlock, 
    StreamBlock,
)

class ImageWithCaptionBlock(StructBlock):
    image = ImageChooserBlock()
    caption = RichTextBlock()


class GalleryBlock(StructBlock):
    # lots of gallery options like “autoadvance”
    items = StreamBlock([
        ('image', ImageWithCaptionBlock()),
        ('video', EmbedBlock()),
    ])    


class FreeFormContentPage(Page):
    body = StreamField([
        ('richtext', RichTextBlock()),
        ('gallery', GalleryBlock()),
    ], use_json_field=True)


class StrictContentPage(Page):
    body = RichTextField()
    gallery = StreamField([
         ('gallery', GalleryBlock()),
    ], use_json_field=True, max_num=1)

这可行,但编辑时看起来有点奇怪

StrictContentPage

我想做的是这样的:


class StrictContentPage(Page):
    body = RichTextField()
    gallery = GalleryBlock()

(或通过调整管理员进行等效操作)

…这样管理体验看起来像:

提前感谢您的指点!

python wagtail wagtail-streamfield
1个回答
0
投票

如果您仍然需要这个,我会以为

StreamBlock
/
StreamField
中的内容创建变量的心态来处理它。

考虑以下示例:

class ImageWithCaptionBlock(StructBlock):
    image = ImageChooserBlock()
    caption = RichTextBlock()

GALLERY_BLOCKS = [
    ('image', ImageWithCaptionBlock()),
    ('video', EmbedBlock()),
]

class GalleryBlock(StructBlock):
    # lots of gallery options like “autoadvance”
    items = StreamBlock(GALLERY_BLOCKS)    

class FreeFormContentPage(Page):
    body = StreamField([
        ('richtext', RichTextBlock()),
        ('gallery', GalleryBlock()),
    ], use_json_field=True)

class StrictContentPage(Page):
    body = RichTextField()
    gallery = StreamField(GALLERY_BLOCKS, use_json_field=True)

此方法将使

StrictContentPage
页面版本的 UI 更具可读性,并保持
FreeFormContentPage
版本相同的用户体验。另外,您不需要冗余代码来更改不同页面类型的字段。

希望这对您有帮助。祝你有美好的一天!

© www.soinside.com 2019 - 2024. All rights reserved.