Django表单中的空选择字段选择 [英] Empty ChoiceField selection in Django forms
本文介绍了Django表单中的空选择字段选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个下拉表单可供选择毕业年份 -
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')#第一个元素将是`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.
这篇关于Django表单中的空选择字段选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文