【发布时间】:2011-11-05 13:54:09
【问题描述】:
我有一个表格(为简洁而编辑)如下:
class InteractionForm(forms.Form):
def __init__(self, *args, **kwargs):
# Each object within this queryset is a model object of type InteractionChoice
choices_qs = interaction.interactionchoice_set.all()
self.fields['choices'] = forms.ModelChoiceField(
widget=forms.RadioSelect(),
queryset=choices_qs,
InteractionChoice 模型如下所示:
class InteractionChoice(models.Model):
interaction = models.ForeignKey(Interaction)
name = models.CharField(max_length=255)
is_answer = models.BooleanField(default=False)
InteractionForm 的实例从视图传递到模板并通过以下方式呈现:
{{ form.choices }}
我的问题是,是否有一种方法可以遍历我的模板中的每个选项并访问它的一个属性——特别是在InteractionChoice 中定义的is_answer 属性。目的是自定义如果确实是答案,选择如何显示。更具体地说,如果 is_answer 为 True,我可能会更改 <label> 上的 class 属性以进行该选择。
也许,我是从错误的方向来解决这个问题的。如果有人有其他想法的建议,我很乐意听到。
提前致谢。
更新 1:
在@rczajka 的回复之后更多地考虑这一点,我不相信我可以在模板代码中实现我希望做的事情。相反,如果目的是修改标签的类属性,我也许应该寻找子类并覆盖forms.widgets.RadioInput、forms.widgets.RadioFieldRenderer 和forms.widgets.RadioSelect 中的某些方法。我会更深入地研究这个。
【问题讨论】:
标签: django django-templates django-forms