0

I've a question about Wagtail CMS.

Recently I'm trying to import programmatically some documents in a StreamField of an instance of a Wagtail Page model. I've done some researches but without results.

Currently I'm using:

  • Wagtail 1.13
  • Django 1.11.6
  • Python 2.7

Here the model of the page in which I need to import the documents as attachments (see the homonym field):

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 = []

On shell, I tried to apply the solution explained on this page but without success.

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

Python give me this error: AttributeError: 'list' object has no attribute 'pk'.

nifel87
  • 17
  • 3

1 Answers1

3

event.attachments = [('document', doc)] should work, I believe. (On the other question you link to, StreamChild was necessary because AccordionRepeaterBlock was a StreamBlock nested in a StreamBlock; that's not the case for your definition.)

To add a document to the existing StreamField content, build a new list and assign that to event.attachments:

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

(Currently you can't append directly to a StreamField value, but this may well be supported in a future Wagtail release...)

gasman
  • 23,691
  • 1
  • 38
  • 56