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. . .
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With