I\'m using Wagtail 2.0 with a custom Block that has the following code:
class LinkButtonBlock(blocks.StructBlock):
label = blocks.CharBlock()
URL = b
The thing that's tripping you up is that the value objects you get when iterating over a StreamField are not instances of StructBlock
. Block objects such as StructBlock
and CharBlock
act as converters between different data representations; they don't hold on to the data themselves. In this respect, they work a lot like Django's form field objects; for example, Django's forms.CharField
and Wagtail's CharBlock
both define how to render a string as a form field, and how to retrieve a string from a form submission.
Note that CharBlock
works with string objects - not instances of CharBlock
. Likewise, the values returned from StructBlock
are not instances of StructBlock
- they are a dict-like object of type StructValue
, and this is what you need to subclass to implement your css
property. There's an example of doing this in the docs: http://docs.wagtail.io/en/v2.0/topics/streamfield.html#custom-value-class-for-structblock. Applied to your code, this would become:
class LinkButtonValue(blocks.StructValue):
@property
def css(self):
# Note that StructValue is a dict-like object, so `styling` and `outline`
# need to be accessed as dictionary keys
btn_class = self['styling']
if self['outline'] is True:
btn_class = btn_class.replace('btn-', 'btn-outline-')
return btn_class
class LinkButtonBlock(blocks.StructBlock):
label = blocks.CharBlock()
URL = blocks.CharBlock()
styling = blocks.ChoiceBlock(choices=[...])
outline = blocks.BooleanBlock(default=False)
class Meta:
icon = 'link'
template = 'testapp/blocks/link_button_block.html'
value_class = LinkButtonValue