如何在 Wagtail CMS 的 StreamField 上添加文档?

How can I add a document on a StreamField in Wagtail CMS?

我有一个关于 Wagtail CMS 的问题。

最近我试图以编程方式在 Wagtail Page 模型实例的 StreamField 中导入一些文档。我做了一些研究,但没有结果。

目前我正在使用:

这里是我需要导入文档作为附件的页面模型(看同音字字段):

class EventPage(TranslatablePage, Page):

# Database fields
uuid = models.UUIDField(verbose_name='UUID', default=uuid.uuid4)
start_date = models.DateField(verbose_name='Start date')
end_date = models.DateField(verbose_name='End date')
location = models.CharField(verbose_name='Place', max_length=255, null=True, blank=True)
body = RichTextField(verbose_name='Body')
attachments = StreamField(blocks.StreamBlock([
    ('document', DocumentChooserBlock(label='Document', icon='doc-full-inverse')),
]), verbose_name='Attachments', null=True, blank=True)
subscribe = models.BooleanField(verbose_name='Subscribe option', default=False)

# Editor panels configuration
content_panels = [
    FieldPanel('title', classname='title'),
    MultiFieldPanel([
        FieldRowPanel([
            FieldPanel('start_date'),
            FieldPanel('end_date'),
        ]),
    ], heading='Period'),
    FieldPanel('location'),
    FieldPanel('body'),
    StreamFieldPanel('attachments'),
]

promote_panels = Page.promote_panels +  [
    MultiFieldPanel([
        FieldPanel('subscribe'),
    ], heading='Custom Settings'),
]

settings_panels = TranslatablePage.settings_panels + [
    MultiFieldPanel([
        FieldPanel('uuid'),
    ], heading='Meta')
]

parent_page_types = ["home.FolderPage"]
subpage_types = []

在 shell 上,我尝试应用在 上解释的解决方案但没有成功。

event = EventPage.objects.get(pk=20)
doc = Document.objects.get(pk=3)
event.attachments = [
    ('document',
        [
            StreamValue.StreamChild(
                id = None,
                block = DocumentChooserBlock(),
                value = doc
            )
        ]
    )
]

Python 给我这个错误:AttributeError: 'list' object has no attribute 'pk'.

event.attachments = [('document', doc)] 应该可以,我相信。 (在 上,StreamChild 是必需的,因为 AccordionRepeaterBlock 是嵌套在 StreamBlock 中的 StreamBlock;您的定义不是这种情况。)

要将文档添加到现有 StreamField 内容,请构建一个新列表并将其分配给 event.attachments

new_attachments = [(block.block_type, block.value) for block in blocks]
new_attachments.append(('document', doc))
event.attachments = new_attachments

(目前您不能直接附加到 StreamField 值,但是 this may well be supported in a future Wagtail release...)