Django:在模板中渲染ModelChoiceField和ChoiceField的显示值

时间:2013-11-13 17:54:57

标签: django django-forms

我有一个ModelChoiceField和一个ChoiceField我需要提取“显示名称”(而不是“值”)。

例如,表单的ModelChoiceField呈现以下输出:

<select name="amodelfield" id="id_amodelfield">
<option value="">---------</option>
<option selected="selected" value="1">ABC</option>
<option value="2">DEF</option>
</select>

我希望能够只选择“ ABC ”,因为它已被选中。如果我按照docs中所述{{ field.value }}进行操作,则会获得值1而不是我想要的ABC。我也有一个ChoiceField,我想要同样的行为。

如果不对ModelChoiceFieldChoiceFieldSelect小部件进行子类化,是否有一种简单的方法可以做到这一点?

编辑:Model.get_FOO_display()在这种情况下不起作用

2 个答案:

答案 0 :(得分:2)

答案 1 :(得分:1)

从@Odif Yltsaeb提供的link开始,我能够使用修改答案中的代码来满足我的需求。这是参考代码:

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

    Modified from:
    https://stackoverflow.com/a/5109986/2891365
    Originally found from:
    https://stackoverflow.com/questions/19960943/django-rendering-display-value-of-a-modelchoicefield-and-choicefield-in-a-templ
    """
    # Explicitly check if boundfield.data is not None. This allows values such as python "False"
    value = boundfield.data if boundfield.data is not None else boundfield.form.initial.get(boundfield.name)
    if value is None:
        return u''
    if not hasattr(boundfield.field, 'choices'):
        return value
    return dict(boundfield.field.choices).get(value, u'')
相关问题