Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the best way to write a combo box in django?

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

like image 855
Alon Weissfeld Avatar asked Nov 22 '14 19:11

Alon Weissfeld


People also ask

What is widget in Django?

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

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())
like image 130
amatellanes Avatar answered Oct 18 '22 20:10

amatellanes


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())
like image 37
Hasan Ramezani Avatar answered Oct 18 '22 18:10

Hasan Ramezani