我有一个简单的ChoiceField,并希望在我的模板渲染过程中访问'selected'项目。
让我们说表单再次显示(由于其中一个字段中的错误),有没有办法做类似的事情:
<h1> The options you selected before was # {{ MyForm.delivery_method.selected }} </h1>
(。selected()无效..)
谢谢!
答案 0 :(得分:5)
@Yuji建议bund_choice_field.data
,但这会返回用户看不到的值(在value="backend-value"
中使用)。在您的情况下,您可能希望用户可以看到文字值(<option>literal value</option>
)。我认为没有简单的方法可以从模板中的选择字段获取字面值。所以我使用模板过滤器来做到这一点:
@register.filter(name='choiceval')
def choiceval(boundfield):
"""
Get literal value from field's choices. Empty value is returned if value is
not selected or invalid.
Important: choices values must be unicode strings.
choices=[(u'1', 'One'), (u'2', 'Two')
"""
value = boundfield.data or None
if value is None:
return u''
return dict(boundfield.field.choices).get(value, u'')
在模板中,它将如下所示:
<h1> The options you selected before was # {{ form.delivery_method|choiceval }} </h1>
更新:我忘了提一件重要的事情,你需要在选择值中使用unicode。这是因为从表单返回的数据始终是unicode。因此,dict(choices).get(value)
如果用于选择的整数,则无法工作。
答案 1 :(得分:2)
{{ myform.delivery_method.data }}
<h1> The options you selected before was # {{ MyForm.delivery_method.data }} </h1>