3

I'm dockerizing my Django application. Since I changed my database from SQLite to Postgres the migration fails and I get this error:

RuntimeWarning: DateTimeField Posts.created_at received a naive datetime (2020-01-19 14:26:30.893128) while time zone support is active.
  warnings.warn("DateTimeField %s received a naive datetime (%s)"
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
psycopg2.errors.CannotCoerce: cannot cast type time without time zone to timestamp with time zone
LINE 1: ..." TYPE timestamp with time zone USING "created_at"::timestam...

I have searched the other issues and tried this fix https://stackoverflow.com/a/20106079/7400518
I was using datetime.now() then I changed it to timezone.now() but I'm still getting the same error. This is the related lines from models.py

from django.utils import timezone

class Posts(models.Model):
    created_at = models.DateTimeField(default=timezone.now(), blank=True)

Saadat
  • 163
  • 4
  • 15
  • 1
    Remove the migration file where it still uses the old `datetime`. Furthermore you should use `auto_now_add`. – Willem Van Onsem Jan 19 '20 at 14:50
  • Does this answer your question? [RuntimeWarning: DateTimeField received a naive datetime](https://stackoverflow.com/questions/18622007/runtimewarning-datetimefield-received-a-naive-datetime) – UrbanConor Mar 08 '23 at 10:18

1 Answers1

2

I was using datetime.now() then I changed it to timezone.now() but I'm still getting the same error.

Changing the model will not change the migration file. You should look up what migration files contain datetime.now(), and remove this (together with all the other migrations that depend on that).

Furthermore using default=timezone.now() is not a good idea. It will use as default the time when you start the webserver. That thus means that if the server runs for two days, the timestamp will still use the timestamp of two days ago.

The DateTimeField has however an auto_now_add=… [Django-doc] to automatically use the timestamp when you add the object:

class Post(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)

This will set the field to blank=True, and editable=False as well.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555