Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django DateField default options

I have a model which has a date time field:

date = models.DateField(_("Date"), default=datetime.now()) 

When I check the app in the built in django admin, the DateField also has the time appended to it, so that if you try to save it an error is returned. How do I make the default just the date? (datetime.today() isn't working either)

like image 744
damon Avatar asked Jan 08 '10 17:01

damon


People also ask

What is Django DateField?

DateField is a field that stores date, represented in Python by a datetime. date instance. As the name suggests, this field is used to store an object of date created in python.

How do I change the default date in Django?

If you want to be able to modify this field, set the following instead of auto_now_add=True : For DateField : default=date.today - from datetime.date.today() For DateTimeField : default=timezone.now - from django.utils.timezone.now()

How do I change the date format in Django?

Python django format date dd/mm/yyyy And, because the format is dd/mm/yyyy, we must use a slash to separate the date, month and year. To separate the day from the month and the month from the year in a date notation we use DateSeparator. The following list will show the valid date separators.


2 Answers

This is why you should always import the base datetime module: import datetime, rather than the datetime class within that module: from datetime import datetime.

The other mistake you have made is to actually call the function in the default, with the (). This means that all models will get the date at the time the class is first defined - so if your server stays up for days or weeks without restarting Apache, all elements will get same the initial date.

So the field should be:

import datetime date = models.DateField(_("Date"), default=datetime.date.today) 
like image 118
Daniel Roseman Avatar answered Sep 19 '22 20:09

Daniel Roseman


Your mistake is using the datetime module instead of the date module. You meant to do this:

from datetime import date date = models.DateField(_("Date"), default=date.today) 

If you only want to capture the current date the proper way to handle this is to use the auto_now_add parameter:

date = models.DateField(_("Date"), auto_now_add=True) 

However, the modelfield docs clearly state that auto_now_add and auto_now will always use the current date and are not a default value that you can override.

like image 26
Eric Palakovich Carr Avatar answered Sep 21 '22 20:09

Eric Palakovich Carr