Only showing year in django admin, a YearField instead of DateField?

odinho - Velmont picture odinho - Velmont · Oct 4, 2009 · Viewed 22.3k times · Source

I've got a model where I need to store birth year. I'm using django admin. The person using this will be filling out loads of people every day, and DateField() shows too much (not interested in the day/month).

This is a mockup model showing how it is now:

class Person(models.Model):
  name = models.CharField(max_length=256)
  born = models.IntegerField(default=lambda: date.today().year - 17)

As you can see, most of the people is 17 years old, so I'm getting their birth year as default.

Can I do this better? How can I make a YearField out of the DateField? If making a YearField I can maybe even make some "easy tags" like the "now" that date has. (Of course, a specialized BornYearField would have easy buttons for 1989, 1990, 1991 and other common years)

Answer

Nils Herde picture Nils Herde · Jul 9, 2014

I found this solution which solves the whole thing quite elegantly I think (not my code):

import datetime
YEAR_CHOICES = []
for r in range(1980, (datetime.datetime.now().year+1)):
    YEAR_CHOICES.append((r,r))

year = models.IntegerField(_('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year)

Edit the range start to extend the list :-)