Toran Billups
Toran Billups

Reputation: 27407

How to use a Django validator to limit dates to 1900 or greater

I found this commit showing the _datere pattern now requires a date > 1900 but ... when I look into django.core.validators today I don't see anything like this (the commit linked to above does say it's from 7 years ago).

What happened to this validation in django and what are people using today in Django 1.4.1 to get this type of validation?

I'm asking this because of the strftime error:

"ValueError('year=1800 is before 1900; the datetime strftime() methods require year >= 1900',)"

Thank you!

Upvotes: 5

Views: 1505

Answers (2)

Chris Pratt
Chris Pratt

Reputation: 239430

@SimeonVisser gave a great explanation of the reason you used to get this exception and why you no longer do.

If still want dates greater than 1900 as business logic and not as an actual inherent limitation, you should be able to use the built-in Django MinValueValidator. Just feed it a date/datetime of 1900-01-01, i.e.

validators=[MinValueValidator(datetime(1900, 1, 1, 0, 0))]

Upvotes: 7

Simeon Visser
Simeon Visser

Reputation: 122496

As of this commit there is a new module django.utils.datetime_safe which supports dates with year < 1900.

You can use strftime from that module if you wish to support dates with year < 1900. Similarly, you can use new_datetime (new_date) to obtain a datetime (date) that supports years < 1900:

value = datetime_safe.new_datetime(value)
# or:
value = datetime_safe.new_date(value)

The other alternative is to write a custom validator yourself for forms and enforce that the year is no less than 1900.

Upvotes: 3

Related Questions