我正在尝试在包含
StructBlock
的鹡鸰中创建一个ChoiceBlock
。这个 choices
的 ChoiceBlock
应该从一个导入中生成,该导入从以前的 id
值中获取一个 ModelChooserBlock
。
但是我做错了什么,因为我无法从
ModelChooserBlock
中读取值来获取它的ID。有没有办法获取ModelChooserBlock
的value.id并将其传递回StructBlock
以生成选择?
查看我的代码:
class StartListBlock(blocks.StructBlock):
"""
Display the start list for a specific race
"""
class Meta:
template = 'blocks/startlist_block.html'
icon = 'site'
label = _('race_startlist')
title = blocks.CharBlock(
required=False,
label=_("title"),
)
# model id will be passed to import race choices
race_day = ModelChooserBlock(
target_model=RaceDay,
label=_("race day"),
)
race = blocks.ChoiceBlock(
required=False,
label=_('race'),
choices=[], # choices will be generated outside the block
)
我试图在
ChoiceBlock
中创建一个新的 get_context
并将其传递回具有新选择的 StructBlock
,但是为了显示选择我需要刷新页面并且所选的比赛值没有传递给上下文。请告知这是否不是正确的方法以及如何完成。
def get_context(self, value, parent_context=None):
context = super().get_context(value, parent_context)
# Get the current value.id of the `race_day` block
race_day_id = value['race_day'].id
# Import choices based on the value of `race_day_id`
race_choices = import_races(value['race_day'].id)
new_race_block = blocks.ChoiceBlock(
choices=race_choices,
label=_('test'),
required=False
)
self.child_blocks['race'] = new_race_block
return context