How to get the label of a choice in a Django forms ChoiceField?


Question

I have a ChoiceField, now how do I get the "label" when I need it?

class ContactForm(forms.Form):
     reason = forms.ChoiceField(choices=[("feature", "A feature"),
                                         ("order", "An order")],
                                widget=forms.RadioSelect)

form.cleaned_data["reason"] would only give me "feature" or "order" or so.

1
59
5/8/2013 12:10:52 PM

Accepted Answer

This may help:

reason = form.cleaned_data['reason']
reason = dict(form.fields['reason'].choices)[reason]
72
9/30/2011 1:19:16 PM

See the docs on Model.get_FOO_display(). So, should be something like :

ContactForm.get_reason_display()

In a template, use like this:

{{ OBJNAME.get_FIELDNAME_display }}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon