11

We're using Django 1.10

We're getting a lot of this warning:

RuntimeWarning: DateTimeField Item.updated_at received a naive datetime (2018-05-01 12:35:18.213471) while time zone support is active.
RuntimeWarning)

I read a lot of answers about that questions, but in that case we're not settings the date manually. That field (Item.updated_at) is set as

auto_now=True

Is there a way to make 'auto_now' not naive?

This is part of the model:

class BaseModel(models.Model):

    id = models.UUIDField(default=uuid.uuid4, editable=False, db_index=True, unique=True, primary_key=True)
    created_by = models.CharField(max_length=200)
    created_at = models.DateTimeField(db_index=True, auto_now_add=True)
    updated_by = models.CharField(max_length=200)
    updated_at = models.DateTimeField(db_index=True, auto_now=True)

Thanks

EDIT: Could it be related to the factories we're using in tests? For example:

class ItemFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Item

    title = "Fake item title"
    identifier = factory.Sequence(lambda n: n)
    status_id = Status.Open['id']
    due_date = None
    updated_by = "Fake updater"
    updated_at = timezone.now()
user2880391
  • 2,683
  • 7
  • 38
  • 77
  • Where are you getting the warning specifically? I've got this before but only in testing, when using the [`model_mommy`](https://github.com/vandersonmota/model_mommy) Django object factory for instance. – toxefa May 01 '18 at 14:45
  • this is a warning, not an error. this answer can help you [RuntimeWarning: DateTimeField received a naive datetime](https://stackoverflow.com/a/20106079/5644965) – Lemayzeur May 01 '18 at 15:48
  • @py4on - I also get it on tests. a lot of this warning. I don't use model_mommy but I do suspect it's related to factories. Did you manage to fix it? – user2880391 May 01 '18 at 19:31
  • @Lemayzeur - Thanks, I know it's a warning and as I mentioned - I saw all existing answers. This case is a bit different – user2880391 May 01 '18 at 19:32
  • I am still getting this in 2021 with Django 3.1, and not in tests – AntonOfTheWoods Mar 10 '21 at 13:42
  • I have the same issue – Vedmant Jun 03 '21 at 10:28

3 Answers3

1

The soultion might be like that:

import datetime
datetime.datetime.now(tz=datetime.timezone.utc)
0

From Django Doc Problem is not in the settings. Hope it will fix your problem

from django.utils import timezone
import datetime

datetime.datetime.now(tz=timezone.utc)
Antu
  • 2,197
  • 3
  • 25
  • 40
0

I ran into a similar issue and resolved it using default value.

from datetime import datetime
.
.
.
updated_at = models.DateTimeField(default=datetime.now)