【问题标题】:How can I add a document on a StreamField in Wagtail CMS?如何在 Wagtail CMS 的 StreamField 上添加文档?
【发布时间】:2017-12-11 11:36:20
【问题描述】:

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

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

目前我正在使用:

  • 鹡鸰 1.13
  • Django 1.11.6
  • Python 2.7

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

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 上,我尝试应用 this page 上解释的解决方案,但没有成功。

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'。

【问题讨论】:

    标签: python django wagtail


    【解决方案1】:

    event.attachments = [('document', doc)] 应该可以工作,我相信。 (在 the other question you link to 上,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...)

    【讨论】:

    • 如果我想在event.attachments 已经包含一些文档时添加一个文档
    猜你喜欢
    • 1970-01-01
    • 2018-09-26
    • 1970-01-01
    • 2016-10-29
    • 2019-01-21
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多