2011-05-22 52 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