Dolidod Teethtard
Dolidod Teethtard

Reputation: 623

How to create custom block in wagtail?

This is my StreamField:

body = StreamField([
    ('heading', blocks.CharBlock(classname="full title")),
    ('paragraph', blocks.RichTextBlock()),
    ('image', ImageChooserBlock()),
])

And my question is: how to add my own Block that I can pass to StreamField? I meant block that contains multiple images, something like block? I didn't find answer for my question in wagtail docs.

Upvotes: 2

Views: 2758

Answers (1)

Chris H
Chris H

Reputation: 101

I meant block that contains multiple images, something like block?

Here is an example of something you could try, I am not sure what specifically you are trying to achieve so I left it fairly generic but modify it how you like.

class GalleryBlock(blocks.StructBlock):
    """
    Nameable gallery with multiple images.
    """
    name = blocks.CharBlock(required=True)
    images = blocks.ListBlock(
        blocks.StructBlock([
            ("image", ImageChooserBlock(required=True)),
            ("alt_text", blocks.CharBlock(required=False, max_length=100)),
        ])
    )

Then you would, of course, need to add this into your StreamField for body.

Something like this maybe.

body = StreamField([
    ('heading', blocks.CharBlock(classname="full title")),
    ('paragraph', blocks.RichTextBlock()),
    ('image', ImageChooserBlock()),
    ('gallery', GalleryBlock(icon='image')), # add this line
])

Hope this helps you see how flexible and awesome these built-in blocks are and how awesome StreamField can be. Sometimes you need to combine them to build a specific structure for your needs.

Upvotes: 6

Related Questions