Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datetime Field Received a Naive Datetime

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

like image 530
user1427661 Avatar asked Dec 11 '13 04:12

user1427661


1 Answers

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())
like image 192
Arthur Rio Avatar answered Sep 23 '22 18:09

Arthur Rio