4

I have a ModelChoiceField and a ChoiceField that I need to pull out the "display name" for (not the "value").

For example, a ModelChoiceField of a form renders the following output:

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

I want to be able to just render "ABC" since it is selected. If I do {{ field.value }} as said in the docs, I get the value 1 instead of the ABC I wanted. I also have a ChoiceField for which I want the same behavior.

Is there a easy way to do this without subclassing ModelChoiceField, ChoiceField and the Select widget?

EDIT: Model.get_FOO_display() would not work in this case

4

2 に答える 2

2

{{ get_fieldname_display }} を使用してください。

https://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.get_FOO_display

于 2013-11-13T17:59:05.313 に答える
1

@Odif Yltsaeb が提供したリンクから、回答のコードを変更して、ニーズに合わせて一般的に機能することができました。参照用のコードは次のとおりです。

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'')
于 2013-11-13T22:47:49.340 に答える