11

I'm going around in circles on this on and need some help. I continue to get a naive timezone warning. Not sure what I am doing wrong! Arg.

Here is the warning:

/django/db/models/fields/__init__.py:1222: RuntimeWarning: DateTimeField Video.modified received a naive datetime (2014-10-07 00:00:00) while time zone support is active.
  RuntimeWarning)

Here is the model code (redacted somewhat):

from django.db import models
from django.utils import timezone

class ItemBase(models.Model):
    created = models.DateTimeField(editable=False)
    modified = models.DateTimeField(editable=False)

    class Meta:
        abstract = True

    def save(self, *args, **kwargs):
        """Updates timestamps on save"""
        if not self.id:
            self.created = timezone.now()
        self.modified = timezone.now()
        return super(ItemBase, self).save(*args, **kwargs)

class Video(ItemBase):
    pass

And the relevant (I think) part of my settings file:

TIME_ZONE = 'UTC'
USE_TZ = True

Is this a sqlite issue (am still testing things)? Or am I missing something fundamental here? I've read up on it here and here and, of course, at the docs here. But I am stumped. Thanks.

edit: added test that throws the error

Am getting the error when I run my tests ... I left the redacted stuff in there but you should get the idea:

from django.test import TestCase
from django.contrib.auth import get_user_model

from video.models import Video, VideoAccount

class VideoTestCase(TestCase):

    def setUp(self):
        user = get_user_model().objects.create_user(
            username='jacob', email='jacob@test.com', password='top_secret')
        self.video_account = VideoAccount.objects.create(
            account_type=1, account_id=12345, display_name="Test Account" )
        self.pk1 = Video.objects.create(video_type=1, video_id="Q7X3fyId2U0",
            video_account=self.video_account, owner=user)

    def test_video_creation(self):
        """Creates a video object"""
        self.assertEqual(self.pk1.video_id, "Q7X3fyId2U0")
        self.assertEqual(self.pk1.video_link, "https://www.youtube.com/watch?v=Q7X3fyId2U0")
Community
  • 1
  • 1
thornomad
  • 6,707
  • 10
  • 53
  • 78
  • when you get this error – Hasan Ramezani Oct 08 '14 at 20:04
  • @HasanRamezani when I am creating a new model in my test suite - sorry, I guess I should have included that ... I can add that in at the bottom! ... and, I don't see that warning in the development server when I add an using the admin ... only when running tests. – thornomad Oct 08 '14 at 20:09
  • remove `USE_TZ = True`, this may fix your problem. – Hasan Ramezani Oct 08 '14 at 20:17
  • 1
    @HasanRamezani - it certainly does remove the warning but I want timezone support! So my problem is not yet fixed. Smile. – thornomad Oct 08 '14 at 20:35
  • What you've posted looks right, so the problem must be somewhere else. Since you say it only happens with tests, try `TransactionTestCase` instead of `TestCase`. It shouldn't matter, but TTC is in general safer. Post your unredacted model code, as well as the exact test command you're running. Do you have multiple settings files? – Kevin Christopher Henry Oct 09 '14 at 04:04
  • @KevinChristopherHenry - I figured it out and posted an answer below ... it was a previous migration that was triggered every time I ran the tests. http://stackoverflow.com/a/26265769/181902 – thornomad Oct 09 '14 at 14:52

3 Answers3

7

So I finally figured it out and I appreciate everyone's input which got me thinking in the right way:

One of my past migrations had datetime.date.today() as the default value (which is a hint the migrations give). I didn't think about it because at the time I didn't even have any data in the model and then, even though that migration had then been migrated again (further down the road), it appears the test system is running every migration each time it starts. So: was getting that warning.

Update: this should be fixed in 1.7.1.

thornomad
  • 6,707
  • 10
  • 53
  • 78
2

You are using SQLite database and SQlite db does not have support for timezones. This is causing the warning.

This warning can be removed by using a different DB backend.

If you want to got with sqlite probably putting these lines in settings file can help:

import warnings
import exceptions
warnings.filterwarnings("ignore", category=exceptions.RuntimeWarning, module='django.db.backends.sqlite3.base', lineno=53)  
umang agarwal
  • 344
  • 2
  • 4
  • Thanks for your comment - I thought it might be sqlite but when I found that snippet (that you included) it did not suppress the warning for me. Which is why I thought it might be something else... I have added it to my `settings.py` file but no luck! – thornomad Oct 08 '14 at 20:34
  • 3
    This is incorrect. The database doesn't need to support timezones because datetimes are always stored in UTC when `USE_TZ = True`. Aware datetimes and SQLite work perfectly well together. – Kevin Christopher Henry Oct 08 '14 at 20:53
  • @KevinChristopherHenry: docs(https://www.sqlite.org/datatype3.html) SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values. Also Error:: RuntimeWarning: DateTimeField Video.modified received a naive datetime (2014-10-07 00:00:00) while time zone support is active... When django tries to read the field value from SQLite db it gets string which has no tz info (For more refer: https://groups.google.com/forum/#!topic/django-developers/duK0htVhq3k) – umang agarwal Oct 08 '14 at 21:30
  • I didn't say that SQLite supported timezones, I said it doesn't *need* to support timezones because datetimes are normalized to UTC before storage. As for that message thread, it is over three years old and predates the introduction of timezone support. If you need more evidence, please note that the [SQLite-specific documentation](https://docs.djangoproject.com/en/dev/ref/databases/#sqlite-notes) doesn't mention any lack of support for aware datetimes. – Kevin Christopher Henry Oct 08 '14 at 22:46
  • 1
    @KevinChristopherHenry I think it has something to do with the testing system; if I run the same series of commands in the `shell` I don't get any `RuntimeWarning` ... not sure what to make of it but I find it obnoxious to say the least! – thornomad Oct 09 '14 at 03:08
0

Have you installed http://pytz.sourceforge.net/ ?

As soon as you activate time zone support, Django needs a definition of the default time zone. When pytz is available, Django loads this definition from the tz database. This is the most accurate solution. Otherwise, it relies on the difference between local time and UTC, as reported by the operating system, to compute conversions. This is less reliable, especially around DST transitions.

Cherif KAOUA
  • 834
  • 12
  • 21