Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Django's form framework for select options?

Tags:

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

Here, it says I can do SELECT widgets. But how do I do that? It doesn't show any example on how to write that field in python.

 <select>
   <option>option 1</option>
   <option>option 2</option>
 </select>
like image 888
TIMEX Avatar asked Jan 24 '11 23:01

TIMEX


People also ask

How do you exclude a specific field from a ModelForm?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.

How do you receive data from a Django form with a post request?

Using Form in a View In Django, the request object passed as parameter to your view has an attribute called "method" where the type of the request is set, and all data passed via POST can be accessed via the request. POST dictionary. The view will display the result of the login form posted through the loggedin.

How do I create a drop down list in Django?

To create a dropdown in Python Django model form, we can create a char field with the choices argument set to a tuple of choices in a model class. Then we can set the model class as the model for the form. to add the color field to the MyModel model class.

What a widget is Django how can you use it HTML input elements?

A widget is Django's representation of an HTML input element. The widget handles the rendering of the HTML, and the extraction of data from a GET/POST dictionary that corresponds to the widget. The HTML generated by the built-in widgets uses HTML5 syntax, targeting <!


2 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>
like image 170
Yuji 'Tomita' Tomita Avatar answered Oct 04 '22 01:10

Yuji 'Tomita' Tomita


CHOICES= (
('ME', '1'),
('YOU', '2'),
('WE', '3'),
)
select = forms.CharField(widget=forms.Select(choices=CHOICES))
like image 40
errx Avatar answered Oct 04 '22 00:10

errx