Creating a TagsBlock for StreamField

允我心安 提交于 2020-04-18 05:48:05

问题


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)


回答1:


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):
        self.field = forms.CharField(widget=AdminTagWidget)
        super().__init__(**kwargs)



回答2:


LB Ben Johnston helped me putting tags into blocks, but I eventually ran into the same error youd did as I couldn't leave the tag field empty. To fix it I modified the above (LB Ben Jonston's answer) so that the the TagsBlock is now:

class TagsBlock(blocks.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):
        self.field = forms.CharField(widget=AdminTagWidget, required=False)
        super().__init__(**kwargs)

The required=False is now inside the self.field.

This allowed me to leave the tag field empty if the user wants to.

Hope that helps!



来源:https://stackoverflow.com/questions/61073812/creating-a-tagsblock-for-streamfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!