Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"] only gives me the feature or order values or so.

like image 864
webjunkie Avatar asked Apr 17 '09 18:04

webjunkie


People also ask

What is form Is_valid () in django?

The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.

How do I customize Modelan in django?

To create ModelForm in django, you need to specify fields. Just associate the fields to first_name and lastName. Under the Meta class you can add : fields = ['first_name','lastName']. @Shishir solution works after I add that line. or you can try solution in Jihoon answers by adding vacant fields.

What is form Cleaned_data in django?

form. cleaned_data returns a dictionary of validated form input fields and their values, where string primary keys are returned as objects. form. data returns a dictionary of un-validated form input fields and their values in string format (i.e. not objects).

How do I remove a form label in django?

In __init__ method set your field label as empty. This will remove label text.


2 Answers

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 }} 
like image 107
shacker Avatar answered Oct 05 '22 15:10

shacker


This may help:

reason = form.cleaned_data['reason'] reason = dict(form.fields['reason'].choices)[reason] 
like image 23
Andrés Torres Marroquín Avatar answered Oct 05 '22 14:10

Andrés Torres Marroquín