Search code examples
djangodjango-modelsdjango-1.7

django models choices list


I am using django 1.7.2 and I have been given some code for a choices list to be placed in a model.

Here is the code:

YOB_TYPES = Choices(*(
    ((0, 'select_yob', _(' Select Year of Birth')),
     (2000, 'to_present', _('2000 to Present'))) +
    tuple((i, str(i)) for i in xrange(1990, 2000)) +
    (1, 'unspecified', _('Prefer not to answer')))
)
....
year_of_birth_type = models.PositiveIntegerField(choices=YOB_TYPES, default=YOB_TYPES.select_yob, validators=[MinValueValidator(1)])
....

The above code gives the incorrect select list as shown below. I have read several SO posts & google searches and scoured the docs, but I am stuck and I am going around in circles.

This is how the current code displays the select list, which is wrong:

enter image description here

However, I want the select list to be displayed as follows:

enter image description here


Solution

  • You should wrap the last tuple in another tuple:

    YOB_TYPES = Choices(*(
        ((0, 'select_yob', _(' Select Year of Birth')),
         (2000, 'to_present', _('2000 to Present'))) +
        tuple((i, str(i)) for i in xrange(1990, 2000)) +
        ((1, 'unspecified', _('Prefer not to answer')),))
    )