views:

3002

answers:

3

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.

+2  A: 

Here is a way I came up with. There may be an easier way. I tested it using python manage.py shell:

>>> cf = ContactForm({'reason': 'feature'})
>>> cf.is_valid()
True
>>> cf.fields['reason'].choices
[('feature', 'A feature')]
>>> for val in cf.fields['reason'].choices:
...     if val[0] == cf.cleaned_data['reason']:
...             print val[1]
...             break
...
A feature

Note: This probably isn't very Pythonic, but it demonstrates where the data you need can be found.

Ryan Duffield
+6  A: 

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 }}
shacker
But it's not a model, it's a form.
webjunkie
A: 

I think maybe @webjunkie is right.

If you're reading from the form from a POST then you would do

def contact_view(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            contact = form.save()
            contact.reason = form.cleaned_data['reason']
            contact.save()
Noel Evans