Django ChoiceField get currently selected

社会主义新天地 提交于 2019-12-22 18:12:16

问题


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>

(.selected() is not working..)

Thanks !


回答1:


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

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



回答2:


@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.



来源:https://stackoverflow.com/questions/5109432/django-choicefield-get-currently-selected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!