我有一个下拉表格供一个人选择毕业年份 --
graduation = forms.ChoiceField(choices=[(x,str(x)) for x in graduation_range])
如何添加一个附加字段并将其设为默认选择/显示?例如,诸如“选择年份”之类的内容。
目前,我正在做--
graduation_range = range(1970,2015)
graduation_range.append('Select Year')
但似乎必须有更直接的方法来做到这一点。 谢谢。
最佳答案
只需添加:
(u'', u'Select Year') # First element will be the `value` attribute.
所以:
choices = [(u'', u'Select Year')]
choices.extend([(unicode(year), unicode(year)) for year in range(1970, 2015)])
graduation = forms.ChoiceField(choices=choices)
顺便说一句,我使用 unicode
是因为您使用的是 str
,但实际上年份字段应该是整数,因为所有年份都是整数。
关于django - Django表单中的空ChoiceField选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6085756/