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
Related videos on Youtube
Author by
tamakisquare
Updated on June 04, 2022Comments
-
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 over 12 yearsThis is a Model field property but ChoiceField is a Form field, so this is not a viable solution.
-
tamakisquare over 12 yearsIndeed, someone posted the same answer earlier and he removed it.
-
tamakisquare over 12 yearsI'll leave this problem open for another day for digging up other solutions, if any.
-
tamakisquare over 12 yearsThanks. After hours of research for a solution to the question, I think custom template tag is my best bet.
-
tamakisquare about 12 yearsYour answer applies to Model fields but the question is regarding Form field, so this is not a solution.
-
tamakisquare about 12 yearsNot to mention, the same answer was already provided by Thibault J a while back then and I responded with the same.
-
conorsch over 9 yearsI used:
return form.fields[field_name].queryset.get(pk=form[field_name].value())
Theform
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. about 7 yearsTo avoid many database hits, I used:
return dict(form.fields[field_name].choices).get(form.initial.get(field_name, None), None)