且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django表单中的空选择字段选择

更新时间:2023-02-12 08:51:59

只需添加:

 (u'',u'Select Year')#第一个元素将是`value`属性。 

所以:

 code> choices = [(u'',u'Select Year')] 
choices.extend([(unicode(year),unicode(year))for range in range(1970,2015)] )
毕业= forms.ChoiceField(选择=选择)

BTW,我使用code> unicode 因为你使用 str ,但实际上一年的字段应该是一个整数,因为所有年份都是整数。 / p>

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 doing --

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.