Reputation: 91
for a Django Model i needed an extra field to set a special month. This was done with the choices attribute an a tuple set:
class Timeline(models.Model):
MONTHS = (
(1, _("January")),
(2, _("February")),
(3, _("March")),
(4, _("April")),
(5, _("May")),
(6, _("June")),
(7, _("July")),
(8, _("August")),
(9, _("September")),
(10, _("October")),
(11, _("November")),
(12, _("December")),
)
tldate_mth = models.IntegerField(_("Month"), choices=MONTHS, default=1)
In admin section this works fantastic. Now i want to output the month in my template:
# ...
def to_string(self):
return "%s (%s / %d)" % (self.title, self.MONTHS.index(self.tldate_mth), self.tldate_yr)
But then i got the message "tuple.index(x): x not in tuple". What did i wrong?
Upvotes: 0
Views: 1023
Reputation: 599796
Django provides you a shortcut do to this: self.get_tldate_mth_display()
.
(The reason your code failed is that that isn't at all what .index()
does; you should just do self.MONTHS[self.tldate_mth-1][1]
; but, as I say, there's no need to do that when there's a built-in way already.)
Upvotes: 1
Reputation: 1103
Try this:
def to_string(self):
return "%s (%s / %d)" % (self.title, [month[0] for month in self.MONTHS].index(self.tldate_mth), self.tldate_yr)
Django stores only the first value of the tuple (values 1-12 in this case) for choices field.
Upvotes: 0