Datetime Field Received a Naive Datetime

4.7k views Asked by At

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. . .

2

There are 2 answers

2
Nilesh On

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.

0
Arthur Rio On

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())