Alex Rivera | Logout

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

Asked 2009-10-04T21:51:59.807
31

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)

Edit
Report

1 Answer

6

You can also do this:

YEARS = (
    ("1990", "1990"),
    ("1991", "1991"),
    ("1992", "1992"),
    # P.e. generate a list from 1960 to date.today().year
    # The reason why they choice key and text value are the
    # same is that if you generate from 1960 to 2060 it will collide.
    #
    # E.g
    # from datetime import datetime
    # def tuplify(x): return (x,x)   # str(x) if needed
    # current_year = datetime.now().year
    # YEARS = map(tuplify, range(1930, current_year + 1))  # range(1,4) gives [1,2,3]
)

class Whatever(models.Model):
    # Show a list with years
    birthdate = models.IntegerField(max_length=2, choices=YEARS)

I hope this will help you.

answered 2010-09-18T13:14:19.227

Your Answer