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

18,155

Solution 1

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]]

Solution 2

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

Share:
18,155

Related videos on Youtube

tamakisquare
Author by

tamakisquare

Updated on June 04, 2022

Comments

  • tamakisquare
    tamakisquare almost 2 years

    I have a ChoiceField in a bound form, whose choices are:

    [('all', 'All users'), ('group', 'Selected groups'), ('none', 'None')]
    

    In the template, I have no problem accessing its bound value (the actual value to be stored; the first element of each tuple) and the choices. With these pieces of info in hands, I know I should be able to access the display values, or the second element of each tuple. But how can I do that in the template? Thanks.

  • tamakisquare
    tamakisquare over 12 years
    This is a Model field property but ChoiceField is a Form field, so this is not a viable solution.
  • tamakisquare
    tamakisquare over 12 years
    Indeed, someone posted the same answer earlier and he removed it.
  • tamakisquare
    tamakisquare over 12 years
    I'll leave this problem open for another day for digging up other solutions, if any.
  • tamakisquare
    tamakisquare over 12 years
    Thanks. After hours of research for a solution to the question, I think custom template tag is my best bet.
  • tamakisquare
    tamakisquare about 12 years
    Your answer applies to Model fields but the question is regarding Form field, so this is not a solution.
  • tamakisquare
    tamakisquare about 12 years
    Not to mention, the same answer was already provided by Thibault J a while back then and I responded with the same.
  • conorsch
    conorsch over 9 years
    I used: return form.fields[field_name].queryset.get(pk=form[field_name].val‌​ue()) The form variable was called while iterating over a formset initialized with queryset=, and its self.data was returning {}. This solution, from the Django IRC logs, solved the problem.
  • Isaac C.
    Isaac C. about 7 years
    To avoid many database hits, I used: return dict(form.fields[field_name].choices).get(form.initial.get(f‌​ield_name, None), None)