Home > Enterprise >  Wagtail - How to set rich text value in nested block (StreamField->StructBlock->RichTextBlock)
Wagtail - How to set rich text value in nested block (StreamField->StructBlock->RichTextBlock)

Time:11-29

I have the following structure:

`class ParagraphWithRelatedLinkBlock(blocks.StructBlock):
    text = blocks.RichTextBlock()
    related_link = blocks.ListBlock(blocks.URLBlock())

class BlogPageSF(Page):
    body = StreamField(
        [
            ("paragraph", ParagraphWithRelatedLinkBlock(),
        ], use_json_field=True
)`

I want to set value of 'text' field from script or Django shell (not via the Wagtail admin site).

How can I do that?

I have tried to do the following in shell:

`p = BlogPageSF()
rt = RichTextBlock('Test')
pb = ParagraphWithRelatedLinkBlock()
pb.text = rt
p.body.append(('paragraph', pb))
p.save()`

I expect that 'text' field in ParagraphWithRelatedLinkBlock will have value of 'Test'

But I get error: AttributeError: 'ParagraphWithRelatedLinkBlock' object has no attribute 'items'

CodePudding user response:

The values you insert into StreamField data should not be instances of the Block class - block instances are only used as part of the stream definition (for example, when you write text = blocks.RichTextBlock(), you're creating an instance of RichTextBlock that forms part of the ParagraphWithRelatedLinkBlock definition).

The correct data types are either simple Python values, such as dict for a StructBlock, or a dedicated value type such as wagtail.rich_text.RichText for a RichTextBlock. So, in the case of ParagraphWithRelatedLinkBlock, you need to supply a dict containing a RichText value:

from wagtail.rich_text import RichText

p = BlogPageSF()
p.body.append(('paragraph', {'text': RichText('Test')}))
p.save()
  • Related