Models.DateField Format issues

Jon picture Jon · Dec 17, 2014 · Viewed 28.4k times · Source

I have a model, which has a date field

date_of_birth = models.DateField(blank=True, null=True, verbose_name="DOB")

I would like to format it to save dates in the format dd/MM/yyyy, but everything I have tried fails.

I think the default must be YYYY-MM-dd because that is how it saves to my database. Trying to submit dates in a different format gives the error:

[u"'17/01/1970' value has an invalid date format. It must be in YYYY-MM-DD format."]

I have tried using Date Widgets but am having a few issues getting it to be compatible with my models.py

Answer

Kevin Brown picture Kevin Brown · Dec 17, 2014

You can change this by overriding input_formats on the DateField in your form. This is covered pretty well in the documentation. The default date formats are

['%Y-%m-%d',      # '2006-10-25'
'%m/%d/%Y',       # '10/25/2006'
'%m/%d/%y']       # '10/25/06'

or

['%Y-%m-%d',      # '2006-10-25'
'%m/%d/%Y',       # '10/25/2006'
'%m/%d/%y',       # '10/25/06'
'%b %d %Y',      # 'Oct 25 2006'
'%b %d, %Y',      # 'Oct 25, 2006'
'%d %b %Y',       # '25 Oct 2006'
'%d %b, %Y',      # '25 Oct, 2006'
'%B %d %Y',       # 'October 25 2006'
'%B %d, %Y',      # 'October 25, 2006'
'%d %B %Y',       # '25 October 2006'
'%d %B, %Y']      # '25 October, 2006'

Depending on whether or not you are using localization in your settings.

You appear to be looking for %d/%m/%y, which isn't a default format.