Cannot make a model @property def-as-field work with wagtail 2.0

前端 未结 1 1333
盖世英雄少女心
盖世英雄少女心 2021-01-20 21:25

I\'m using Wagtail 2.0 with a custom Block that has the following code:

class LinkButtonBlock(blocks.StructBlock):
    label = blocks.CharBlock()
    URL = b         


        
1条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-20 22:00

    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
    

    0 讨论(0)
提交回复
热议问题