2011-05-22 54 views
3

我有一个下拉的形式来选择自己的毕业年 -空ChoiceField选择形成

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

我将如何添加其他字段,并默认选择/显示?例如,“选择年”等。

目前,我正在做 -

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

但似乎必须有这样做更直接的方式。 谢谢。

回答

6

只需添加:

(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,但实际上一年场或许应该是一个整数,因为所有年份都整数。

+0

,什么是需要的领域时,会发生什么?那么即使用户没有选择一个值,表单也会被提交。 – user1919 2016-06-09 11:21:05

1

我用了Django的1.8