Django datetime issues (default=datetime.now())
it looks like datetime.now()
is being evaluated when the model is defined, and not each time you add a record.
Django has a feature to accomplish what you are trying to do already:
date = models.DateTimeField(auto_now_add=True, blank=True)
or
date = models.DateTimeField(default=datetime.now, blank=True)
The difference between the second example and what you currently have is the lack of parentheses. By passing datetime.now
without the parentheses, you are passing the actual function, which will be called each time a record is added. If you pass it datetime.now()
, then you are just evaluating the function and passing it the return value.
More information is available at Django's model field reference
Django default=datetime.now() in models always saves same datetime after uwsgi reset
default=datetime.datetime.now()
is evaluated at parsing/compile time of the model. It is not changed afterwards. To evaluate now()
at the time of adding/updating an object, you have to use:
default=datetime.datetime.now
, which sets now
as the callable. Django will call it at runtime.
Your solution of using auto_now_add
is of course also correct (yet semantically different -- passing a default will set the value every time the model is saved, whereas auto_now_add
only does it once, at creation time).
Don't dispair, this is avery common mistake.
Django DateTimeField and datetime.datetime.now() giving different times
This is a pretty common gotcha in Django's world. The post mentioned by @eliakin-costa discuss this problem, although his solution works I wouldn't recommend overriding save
method to get this behavior as it's easier to create a function (keeping decoupled and explicit):
from django.db import models
from django.utils import timezone
def default_image_name():
return timezone.now().strftime("%Y%m%d-%H%M%S")
class Image(models.Model):
name = models.CharField(max_length=255, default=default_image_name)
create_date = models.DateTimeField(auto_now_add=True)
image = models.ImageField(upload_to="images/")
By the way, did you take a look at this docs (upload_to
also accepts a callable) ? Do you really need a name
column in your table?
Django - Can't set default DateTimeField value
I've figured out, that the problem is with django-admin. If I'll use code like this:
new_event = Event(title="blablah", text="some_text")
new_event.save()
then it saves DateField
properly using default=timezone.localtime
.
Probably django-admin tried to pass empty string to DateField
instead of not touching it and letting it take default action.
Django models: default datetime is not translated into SQL CURRENT_TIMESTAMP
However, when I inspect my DB outside of Django, the default timestamp doesn't show up.
That is correct, Django itself manages the default values. Not the database, Django also manages the ON DELETE
trigger, not the database. This gives more flexibility. For example you can pass a callable to the default
like you did with default=now
. This callable can perform sophisticated actions to determine the default value like making extra queries, API calls, file I/O, etc. This is not possible with a default at the database side.
You can make a data migration file and manually alter the table. You can initialize a data migration with:
python manage.py makemigrations --empty app_name
next you can alter the file it has generated and specify a default with:
# Generated by Django 3.1 on 2020-12-16 17:14
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('app_name', 'migration_name'),
]
operations = [
migrations.RunSQL(
'ALTER TABLE table_name ALTER COLUMN created_at SET DEFAULT CURRENT_TIMESTAMP';
)
]
The advantage of doing this is that Django manages the migrations, and it will thus migrate the databases that have not been migrated and thus add a default value.
Related Topics
Exif Manipulation Library for Python
Too Many Different Python Versions on My System and Causing Problems
How to Catch a Numpy Warning Like It's an Exception (Not Just for Testing)
How to Normalize a Numpy Array to a Unit Vector
How Does This Input Work with the Python 'Any' Function
How to Get Most Informative Features for Scikit-Learn Classifiers
Matplotlib Legend Markers Only Once
Pandas Dataframe Concat VS Append
Mysql-Python Install Error: Cannot Open Include File 'Config-Win.H'
Python How to Pad Numpy Array with Zeros
Pipe Subprocess Standard Output to a Variable
Reference List Item by Index Within Django Template
Pandas Dataframe with Multiindex Column - Merge Levels
Nested for Loops Using List Comprehension
Nonlocal Keyword in Python 2.X