问题
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