Datetime Field Received a Naive Datetime
Asked Answered
N

2

17

I'm running into the classic DateTimeField received a naive datetime while time zone support is active warning with a twist. The error occurs when I run tests that utilize factories provided by factory_boy. Here is an example of a factory:

from django.utils.timezone import now
import factory
class PostFactory(factory.DjangoModelFactory):
    FACTORY_FOR = models.Post
    value = 42
    created = now()

As you can see, I'm using the now() method from Django's timezone, which should take care of the whole naive datetime thing, but it doesn't. Here's what the model looks like:

class Post(models.Model)
    value = models.IntegerField()
    created = models.DateTimeField(auto_now_add=True)

Also, in my settings.py file, I have set USE_TZ = True.

I've tried installing pytz and using its libraries to create a datetime object to populate the field in the factory, but that doesn't work either.

I know I can suppress the warning, but it's already starting to bite me in other areas of the code, and I'd like to get to the bottom of it. . .

Noticeable answered 11/12, 2013 at 4:40 Comment(5)
d.u.t.now() returns an aware object if USE_TZ=TrueGoverness
I know. That's why I'm confused by the error I'm getting, since I'm using d.u.t.now() to fill in the DateTimeField.Noticeable
Are you sure this part of code gives you the warning?Notogaea
I can't think of where else would if I'm just running tests and factory boy is the only thing populating the DB...Noticeable
Hi, I was wondering you were able to fix this @NoticeableWadewadell
W
25

You can use faker as follows:

import factory
from django.utils import timezone


class PostFactory(factory.DjangoModelFactory):
    FACTORY_FOR = models.Post
    value = 42
    created = factory.Faker("date_time", tzinfo=timezone.get_current_timezone())
Wrought answered 12/4, 2019 at 14:17 Comment(0)
I
0

You need to change timezone in settings.py also.

When USE_TZ is False, this is the time zone in which Django will store all datetimes. When USE_TZ is True, this is the default time zone that Django will use to display datetimes in templates and to interpret datetimes entered in forms.

Isaacisaacs answered 11/12, 2013 at 4:42 Comment(2)
forgot to mention, I have USE_TZ set to True already. Updated post to reflect thatNoticeable
It's not working. I just forgot to mention that the not working code already has USE_TZ set to True.Noticeable

© 2022 - 2024 — McMap. All rights reserved.