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)
For a solution not involving Model choices:
That'll also create a placeholder in the input field with the value of
help_text
.I found this solution which solves the whole thing quite elegantly I think (not my code):
Edit the range start to extend the list :-)
You can also do this:
I hope this will help you.
Also, and this isn't that relevant for your case, but is useful being aware of, don't use datetime.date.today(), or datetime.datetime.now() as defaults. This is executed once, when the server is started up.
You are much better off passing the callables in:
Note, you could use a lambda to make it relative:
Of course, this is naive, and assumes there have been 5 leap years in the past 17 years.