Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 948
tamakisquare Avatar asked Dec 08 '11 01:12

tamakisquare


People also ask

What is a choicefield in Django forms?

Last Updated : 13 Feb, 2020 ChoiceField in Django Forms is a string field, for selecting a particular choice out of a list of available choices. It is used to implement State, Countries etc. like fields for which information is already defined and user has to choose one. It is used for taking text inputs from the user.

How to display the reason of a form in Django?

reason = form.cleaned_data ['reason'] reason = dict (form.fields ['reason'].choices) [reason] Django allows grouped choices. If you have those, this won't work. This the easiest way to do this: Model instance reference: Model.get_FOO_display () You can use this function which will return the display name: ObjectName.get_FieldName_display ()

How can I learn more about how Django works?

You can learn a lot by reading the built-in templates to see how they construct the widgets. The Django Debug Toolbar also presents a lot of information about how a page is constructed and rendered. [Late Edit] Also see RadioSelect oh okay. thank you for the links.

What is the use of localize in Django forms?

The localize argument enables the localization of form data input, as well as the rendered output. disabled. The disabled boolean argument, when set to True, disables a form field using the disabled HTML attribute so that it won’t be editable by users. How to customize Django forms using Django Widget Tweaks ?


1 Answers

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]]
like image 170
bmihelac Avatar answered Sep 21 '22 19:09

bmihelac