Django表单中的空ChoiceField选择

Dav*_*542 3 django django-forms

我有一个下拉表单供选择毕业年份 -

graduation = forms.ChoiceField(choices=[(x,str(x)) for x in graduation_range])
Run Code Online (Sandbox Code Playgroud)

如何添加其他字段并将其设为默认选择/显示?例如,"选择年份"之类的东西.

目前,我在做 -

graduation_range = range(1970,2015)
graduation_range.append('Select Year')
Run Code Online (Sandbox Code Playgroud)

但似乎必须有一种更直接的方式来做到这一点.谢谢.

oro*_*aki 7

只需添加:

(u'', u'Select Year')  # First element will be the `value` attribute.
Run Code Online (Sandbox Code Playgroud)

所以:

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

BTW,我unicode之所以使用str,是因为你正在使用,但实际上一年的字段应该是一个整数,因为所有年份都是整数.