开发者

Django ChoiceField get currently selected

I have a simple ChoiceField and want to access the 'selected' item during my template rendering.

Lets say the form gets show again (due to error in one of the fields), is there a way to do something like:

<h1> The options you selected before was # {{ MyForm.delivery_method.selected }} </h1>

(.selecte开发者_开发知识库d() is not working..)

Thanks !


@Yuji suggested bund_choice_field.data, however that will return value which is not visible to user (used in value="backend-value"). In your situation you probably want literal value visible to user (<option>literal value</option>). I think there is no easy way to get literal value from choice field in template. So I use template filter which does that:

@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'')

In template it will look like this:

<h1> The options you selected before was # {{ form.delivery_method|choiceval }} </h1>

UPDATE: I forgot to mention an important thing, that you will need to use unicode in choice values. This is because data returned from form is always in unicode. So dict(choices).get(value) wont work if integers where used in choices.


It would be accessed by {{ myform.delivery_method.data }}

<h1> The options you selected before was # {{ MyForm.delivery_method.data }} </h1>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜