How to get shortcut of choice in Django Form ChoiceField?

I have a ChoiceField, now how do I get a “tag” 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"] will only provide me with a "function" or an "order" or so.

+50
python django
Apr 17 '09 at 18:43
source share
7 answers

This can help:

 reason = form.cleaned_data['reason'] reason = dict(form.fields['reason'].choices)[reason] 
+57
Sep 29 '11 at 17:14
source share

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

 ContactForm.get_reason_display() 

In the template, use the following:

 {{ OBJNAME.get_FIELDNAME_display }} 
+101
Apr 18 '09 at 3:28
source share

This is the easiest way to do this: Link to the model instance: Model.get_FOO_display ()

You can use this function to return the display name: ObjectName.get_FieldName_display()

Replace ObjectName with your class name and FieldName , in the field of which you need to get the display name.

+15
Mar 05 2018-12-21T00:
source share

If the form instance is linked, you can use

 chosen_label = form.instance.get_FOO_display() 
+6
Apr 7 2018-12-12T00:
source share

This is how I came up with. There may be an easier way. I tested it with 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 is probably not very Pythonic, but it shows where to find the data.

+3
Apr 17 '09 at 20:06
source share

You may have your form:

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

Then it will give you what you want:

 reason = dict(CHOICES)[form.cleaned_data["reason"]] 
+2
May 9 '12 at 11:20
source share

I think maybe @webjunkie is right.

If you read the form from POST, 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() 
0
Oct. 25 '10 at
source share



All Articles