Django ChoiceField目前被选中

Bor*_*ris 2 django django-templates django-forms

我有一个简单的ChoiceField,并希望在我的模板渲染过程中访问"选定"项.

让我们说表单再次显示(由于其中一个字段中的错误),有没有办法做类似的事情:

<h1> The options you selected before was # {{ MyForm.delivery_method.selected }} </h1>
Run Code Online (Sandbox Code Playgroud)

(.selected()不起作用..)

谢谢 !

Ski*_*Ski 5

@Yuji建议bund_choice_field.data,但是这将返回用户不可见的值(用于value="backend-value").在您的情况下,您可能希望user(<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'')
Run Code Online (Sandbox Code Playgroud)

在模板中,它将如下所示:

<h1> The options you selected before was # {{ form.delivery_method|choiceval }} </h1>
Run Code Online (Sandbox Code Playgroud)

更新:我忘了提一件重要的事情,你需要在选择值中使用unicode.这是因为从表单返回的数据始终是unicode.因此,dict(choices).get(value)如果用于选择的整数,则不会工作.