Empty ChoiceField Selection in Django Forms

I have a drop-down list to select the graduation year -

graduation = forms.ChoiceField(choices=[(x,str(x)) for x in graduation_range])

How would I add an extra field and make it default / display? For example, something like "Choose year."

I'm currently doing -

graduation_range = range(1970,2015)
graduation_range.append('Select Year')

But there seems to be a more direct way to do this. Thank.

+3
source share
2 answers

Just add:

(u'', u'Select Year')  # First element will be the `value` attribute.

So:

choices = [(u'', u'Select Year')]
choices.extend([(unicode(year), unicode(year)) for year in range(1970, 2015)])
graduation = forms.ChoiceField(choices=choices)

By the way, I used unicodebecause you used str, but in practice the field of the year should be an integer, since all years are integers.

+6
source
#city choices
city_list=city.objects.all()
choices_city = ([('----select----','----select a city----')])
choices_city.extend([(x,x) for x in city_list])
city =forms.CharField(widget=forms.Select(choices=choices_city))

I used it for django 1.8

+1
source

All Articles