Also, block.value.styling and block.value.outline on their own work just fine, so... what am I doing wrong here?推荐答案让您感到困惑的是,您在遍历 StreamField 时获得的值对象不是 StructBlock 的实例.StructBlock 和 CharBlock 等块对象充当不同数据表示之间的转换器;他们不会自己保留数据.在这方面,它们的工作方式很像 Django 的表单字段对象;例如,Django 的 forms.CharField 和 Wagtail 的 CharBlock 都定义了如何将字符串呈现为表单字段,以及如何从表单提交中检索字符串.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.请注意,CharBlock 适用于字符串对象 - 而不是 CharBlock 的实例.同样,从 StructBlock 返回的值不是 StructBlock 的实例 - 它们是 StructValue 类型的类似 dict 的对象,并且 this 是实现 css 属性所需的子类.在文档中有一个这样做的例子:http://docs.wagtail.io/en/v2.0/topics/streamfield.html#custom-value-class-for-structblock.应用于您的代码,这将变成: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_classclass 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 这篇关于无法使模型 @property def-as-field 与 wagtail 2.0 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-20 12:43