Alon Weissfeld
Alon Weissfeld

Reputation: 1325

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

Upvotes: 7

Views: 19617

Answers (2)

amatellanes
amatellanes

Reputation: 3735

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())

Upvotes: 14

Hasan Ramezani
Hasan Ramezani

Reputation: 5194

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())

Upvotes: 5

Related Questions