104

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)

8 Answers 8

172

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)
10
  • 1
    @Joe J: this should be a new question really. But the fact that you can use a callable means you can just define your own function that returns today+4. Feb 21, 2011 at 20:38
  • 34
    What is _("Date") doing?
    – benregn
    Aug 5, 2011 at 18:50
  • 17
    @benregn It's giving the field a label of "Date" but marking it for translation using the internationalization system. Aug 5, 2011 at 19:17
  • 1
    Thanks for clarifying that, I've just started Django dev and it was a bit unclear to me if it was doing more that just labeling.
    – benregn
    Aug 6, 2011 at 5:49
  • 1
    @benregn You'll need to include from django.utils.translation import gettext as _ for internationalization
    – jdero
    Nov 2, 2016 at 20:16
53

Your mistake is using the datetime class instead of the date class. 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.

1
  • Nice to know about auto_now_add. One thing to be aware of though is that it creates a read-only field, which is unfortunate, though it makes sense for auto_now.
    – Ryan H.
    Mar 13, 2021 at 18:30
7
date = models.DateTimeField(default=datetime.now, blank=True)
2
  • 7
    DateTimeField is not the same. If you provide a datetime as default to a DateField, you'll have trouble. Dec 17, 2017 at 10:41
  • 1) The question is about DateField and 2) using datetime.now (a naive timezone) instead of timezone.now may have unwanted consequences. So this answer is double-trouble.
    – Jarad
    Dec 29, 2022 at 22:57
6

I think a better way to solve this would be to use the datetime callable:

from datetime import datetime

date = models.DateField(default=datetime.now)

Note that no parenthesis were used. If you used parenthesis you would invoke the now() function just once (when the model is created). Instead, you pass the callable as an argument, thus being invoked everytime an instance of the model is created.

Credit to Django Musings. I've used it and works fine.

5

DateField/DateTimeField.auto_now_add

Automatically set the field to now when the object is first created. Useful for creation of timestamps. Note that the current date is always used; it’s not just a default value that you can override. So even if you set a value for this field when creating the object, it will be ignored.
Source: Django doc

This should do the trick:

models.DateTimeField(_("Date"), auto_now_add = True)
2
4

You could also use lambda. Useful if you're using django.utils.timezone.now

date = models.DateField(_("Date"), default=lambda: now().date())
3
  • 10
    Look at documentation. It is not good to use lambda as default callable wrapper: Note that lambdas cannot be used for field options like default because they cannot be serialized by migrations. See that documentation for other caveats.
    – pulina
    Mar 17, 2015 at 13:27
  • @pulina you're right, but in this case when you need date binded to configured timezone this looks like the only solution
    – oxfn
    Dec 18, 2019 at 22:27
  • 1
    Nope. You can point a actual function in code. Any function or method reference according to this in connection that is model top level function.
    – pulina
    Feb 6, 2020 at 12:02
0

django hint:

HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use django.utils.timezone.now

0

I tried the below on Django version 4.1.7 and worked perfectly!

from datetime import datetime, date

class Example(models.Model):
    purchase_date = models.DateField(auto_now_add=False, auto_now=False, blank=True)

    def __str__(self):
        return f"{self.str(purchase_date)}"

Returning this is entirely optional. Working perfectly either you return the string or not.

1
  • This python is full of syntax errors and basic linter issues. I tried to correct some in my edit, but realized this may have been generated by AI or something. To name a few issues: unnecessary import, __str__ causes infinite recursion, also passes arg to self.str(...) which doesn't take arguments. Perhaps most importantly, this does not satisfy the original question: how do you set a datetime default on a django model field?
    – damon
    Mar 17, 2023 at 16:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.