3

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.

David542
  • 104,438
  • 178
  • 489
  • 842

2 Answers2

7

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.

orokusaki
  • 55,146
  • 59
  • 179
  • 257
  • 1
    And what happens when the field is required? Then even if the user doesn't select a value then the form is submitted. – user1919 Jun 09 '16 at 11:21
1
#city choices
city_list=city.objects.all()
choices_city = ([('----select----','----select a city----')])
choices_city.extend([(x,x) for x in city_list])
city =forms.CharField(widget=forms.Select(choices=choices_city))

I used it for django 1.8

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441