How to use Django form structure to select options?

http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Select

It says that I can make SELECT widgets. But how do I do this? There is no example on how to write this field in python.

 <select>
   <option>option 1</option>
   <option>option 2</option>
 </select>
+5
source share
3 answers
class MyForm(forms.Form):
    CHOICES = (('Option 1', 'Option 1'),('Option 2', 'Option 2'),)
    field = forms.ChoiceField(choices=CHOICES)

print MyForm().as_p()

# out: <p><label for="id_field">Field:</label> <select name="field" id="id_field">\n<option value="Option 1">Option 1</option>\n<option value="Option 2">Option 2</option>\n</select></p>
+5
source
CHOICES= (
('ME', '1'),
('YOU', '2'),
('WE', '3'),
)
select = forms.CharField(widget=forms.Select(choices=CHOICES))
+10
source

The errx solution was almost correct in my case: the work was in progress (django v1.7x):

CHOICES= (
('1','ME'),
('2','YOU'),
('3','WE'),
)
select = forms.ChoiceField(widget=forms.Select, choices=CHOICES)

Elements inside CHOICES match ($ option_value, $ option_text).

+6
source

All Articles