I try making a combo box in django. I only found doing it with HTML. Is there a form based django code to do it? For example I want a combo box with cities that I can select and then choose and hit submit to send the city to another page. thanks
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 <!
If you have a static list of cities, you can create a combobox using ChoiceField
:
from django import forms
class SelectCityForm(forms.Form):
CITY_1 = 'city_1'
CITY_2 = 'city_2'
CITY_CHOICES = (
(CITY_1, u"City 1"),
(CITY_2, u"City 2")
)
cities = forms.ChoiceField(choices=CITY_CHOICES)
IF you are saving cities into the database, you can use ModelChoiceField
:
class SelectCityForm(forms.Form):
cities = forms.ModelChoiceField(queryset=City.objects.all())
If you have a list of cities, you can use create a form
like this:
class myForm(forms.Form):
city_list = ['city1','city2']
city = forms.ChoiceField(choices=city_list)
But, if your cities goes from your model you can use use this:
class myForm(forms.Form):
city = forms.ModelChoiceField(queryset=City.objects.all())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With