[Fixed]-Django: How to access the display value of a ChoiceField in template given the actual value and the choices?

13👍

I doubt that it can be done without custom template tag or filter.
Custom template filter could look:

@register.filter
def selected_choice(form, field_name):
    return dict(form.fields[field_name].choices)[form.data[field_name]]

5👍

Use the get_FOO_display property.

** Edit **

Oups! Quick editing this answer, after reading the comments below.

bound_form['field'].value()

Should work according to this changeset

0👍

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

You can use this function which will return the display name – ObjectName.get_FieldName_display()

Replace ObjectName with your class name and FieldName with the field of which you need to fetch the display name of.

👤Kumar

0👍

I have a contact form using the FormView class-based view. The contact form has some ChoiceField fields. I’m not storing the submissions in the database; just emailing them to the site owner. This is what I ended up doing:

def form_valid(self, form):
    for field in form.fields:
        if hasattr(form[field].field, 'choices'):
            form.cleaned_data[field + '_value'] = dict(form[field].field.choices)[form.cleaned_data[field]]

    ...
👤Nick

-1👍

If you use {{ form.instance.field }} in the form template, it should display the selected choice display name

👤NMC

-1👍

After not being able to use get_FOO_display due to using the ‘union’ method (As it returns a dictionary, not a list of objects). I wrote a quick template tag to convert the field display.

@register.simple_tag
def tag_get_display(obj):
    """
        Returns the display of the field when unable to access get_foo_display.

    """
    return CHOICES_LIST[obj][1]

Leave a comment