开发者

Empty ChoiceField selection in Django forms

开发者 https://www.devze.com 2023-03-07 07:40 出处:网络
I have a dropdown form for one to select their graduation year -- graduation = forms.ChoiceField(choices=[(x,str(x)) for x in graduation_range])

I have a dropdown form for one to select their graduation year --

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

How would I add an additional field and make that the default selection/display? For example, something like "Select Year".

Currently, I'm doin开发者_运维技巧g --

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

But it seems there must be a more straight-forward way to do this. Thank you.


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)

BTW, I used unicode because you were using str, but in practice a year field should probably be an integer, since all years are integers.


#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

0

精彩评论

暂无评论...
验证码 换一张
取 消