wagtailwagtail-streamfield

Creating a TagsBlock for StreamField


I'm trying to create a struck block, which has a tags field so the user could choose the tags he wants to filter from. I created the tags field using wagtail.admin.widgets import AdminTagWidget.

class TagsBlock(FieldBlock):
    field = forms.CharField(
        widget=AdminTagWidget
        )

class RelatedArticlesBlock(StructBlock):
    title = CharBlock(required=False)
    filter_tags = TagsBlock()
    no_of_items = IntegerBlock()

It works as expected for selecting tags. But when I save it gives validation errors because the filter_tags field is empty.

What should I do to fix this? (The input is not populating with the selected tags)

Works as expected for selecting tags

Validation errors because the filter_tags field is empty


Solution

  • A slight refinement, setting the field in the __init__ call appears to work.

    Based on the docs relating to custom block types.

    from django import forms
    
    from wagtail.admin.widgets import AdminTagWidget
    
    # ...
    
    class TagsBlock(FieldBlock):
        """
        Basic Stream Block that will use the Wagtail tags system.
        Stores the tags as simple strings only.
        """
    
        def __init__(self, required=False, help_text=None, **kwargs):
            # note - required=False is critical if you are adding this block to an existing streamfield (or you can set up your manual migrations to avoid this need)
            self.field = forms.CharField(widget=AdminTagWidget, required=False)
            super().__init__(**kwargs)