28

I am trying to test a cart creation based on django cart

But I have this error when I am trying to create the cart :

RunTimeWarning : DateTimeField received a naive datetime while time zone support is active

I did some research but I couldn't resolve my problem for datetime.datetime.now()

test_views.py in my tests directory :

from django.test import TestCase, Client, RequestFactory
import unittest
from django.contrib.auth.models import User, AnonymousUser
from front.models import Entreprise, Cart, CartItems
from decimal import Decimal
from front.cart import models
import datetime
import pytz
from pytz import all_timezones
from django.utils import timezone



def _create_cart_in_database(self, creationDate=datetime.datetime.now(), checkedOutDate=True):
    """
        Helper function so I don't repeat myself
    """
    cart = models.Cart()
    cart.creationDate = creationDate
    cart.checkedOutDate = False
    cart.save()
    return cart


def test_cart_creation(self):
    creationDate = datetime.datetime.now()
    cart = self._create_cart_in_database(creationDate)
    id = cart.id

    cart_from_database = models.Cart.objects.get(pk=id)
    self.assertEquals(cart, cart_from_database)

models.py :

class Cart(models.Model):
    creationDate = models.DateTimeField()

I also have USE_TZ = True in my settings.

I tried timezone.now() but still doesn't work :

def _create_cart_in_database(self, creationDate=timezone.now(), checkedOutDate=True):

def test_cart_creation(self):
    creationDate = timezone.now()

RunTimeWarning : DateTimeField Cart.creationDate received a naive datetime (2016-06-03 08:46:34.829000) while time zone support is active.

EDIT :

I have this error now and it seems an error format datetime ?

    updated = self._save_table(raw, cls, force_insert, force_update, using, upda
te_fields)
  File "C:\Python27\lib\site-packages\django-1.9.5-py2.7.egg\django\db\models\ba
se.py", line 820, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "C:\Python27\lib\site-packages\django-1.9.5-py2.7.egg\django\db\models\ba
se.py", line 859, in _do_insert
    using=using, raw=raw)
  File "C:\Python27\lib\site-packages\django-1.9.5-py2.7.egg\django\db\models\ma
nager.py", line 122, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Python27\lib\site-packages\django-1.9.5-py2.7.egg\django\db\models\qu
ery.py", line 1039, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "C:\Python27\lib\site-packages\django-1.9.5-py2.7.egg\django\db\models\sq
l\compiler.py", line 1059, in execute_sql
    for sql, params in self.as_sql():
  File "C:\Python27\lib\site-packages\django-1.9.5-py2.7.egg\django\db\models\sq
l\compiler.py", line 1019, in as_sql
    for obj in self.query.objs
  File "C:\Python27\lib\site-packages\django-1.9.5-py2.7.egg\django\db\models\sq
l\compiler.py", line 958, in prepare_value
    value = field.get_db_prep_save(value, connection=self.connection)
  File "C:\Python27\lib\site-packages\django-1.9.5-py2.7.egg\django\db\models\fi
elds\__init__.py", line 728, in get_db_prep_save
    prepared=False)
  File "C:\Python27\lib\site-packages\django-1.9.5-py2.7.egg\django\db\models\fi
elds\__init__.py", line 1461, in get_db_prep_value
    value = self.get_prep_value(value)
  File "C:\Python27\lib\site-packages\django-1.9.5-py2.7.egg\django\db\models\fi
elds\__init__.py", line 1440, in get_prep_value
    value = super(DateTimeField, self).get_prep_value(value)
  File "C:\Python27\lib\site-packages\django-1.9.5-py2.7.egg\django\db\models\fi
elds\__init__.py", line 1296, in get_prep_value
    return self.to_python(value)
  File "C:\Python27\lib\site-packages\django-1.9.5-py2.7.egg\django\db\models\fi
elds\__init__.py", line 1399, in to_python
    parsed = parse_datetime(value)
  File "C:\Python27\lib\site-packages\django-1.9.5-py2.7.egg\django\utils\datepa
rse.py", line 93, in parse_datetime
    match = datetime_re.match(value)
TypeError: expected string or buffer
Selcuk
  • 57,004
  • 12
  • 102
  • 110
William P.
  • 335
  • 1
  • 4
  • 7
  • Aside from Selcuk's answer, you might want to avoid setting the methods default to the `now()` method. I'm pretty sure it won't be executed every time you call the function... just when first initialized – Sayse Jun 03 '16 at 06:51
  • @Sayse So do you any idea about how I can give another date instead of now() ? – William P. Jun 03 '16 at 06:59
  • `now` is correct (and I suspect you may still be running the old code and may need to restart the dev server). Simpy set the default to `None` and then check inside the method if it is none and if so set it to now inside of it – Sayse Jun 03 '16 at 07:01
  • @Sayse I restarted the server but nothing changed. I am so sorry but could I ask you where and how I set the default to None ? I am still a newbie ... – William P. Jun 03 '16 at 07:18
  • `def _create_cart_in_database(self, creationDate=None..` – Sayse Jun 03 '16 at 07:22
  • @Sayse I set the default to None but he continues to give me the same error with actual datetime ... – William P. Jun 03 '16 at 07:35
  • William P, that wouldn't stop this error, it would stop a different one from occuring. You should try to create a [mcve], the given duplicate and Selcuks answer should solve the problem. – Sayse Jun 03 '16 at 07:39
  • this is curious. can you try "models.DateTimeField(auto_now_add = True)" and let us know what happens – Aditya Pandhare Jun 03 '16 at 07:47
  • @AdityaPandhare I tried your solution and I edited my post where you can find the new error – William P. Jun 03 '16 at 08:18
  • if you can, clear up your migrations and try it once more. refer to http://stackoverflow.com/questions/27220480/django-datetime-migration-error – Aditya Pandhare Jun 03 '16 at 09:04
  • Does this answer your question? [RuntimeWarning: DateTimeField received a naive datetime](https://stackoverflow.com/questions/18622007/runtimewarning-datetimefield-received-a-naive-datetime) – UrbanConor Mar 08 '23 at 10:18

1 Answers1

67

The following line creates a naive (non-timezone aware) datetime:

creationDate = datetime.datetime.now()

Try changing that line to:

creationDate = timezone.now()

Don't forget to import timezone at the beginning of your code:

from django.utils import timezone
Selcuk
  • 57,004
  • 12
  • 102
  • 110
  • 1
    Here the timezone would be the server's timezone right? What should we do if there are users across different timezones and we want to record their time zones? – Mukund Gandlur Jun 03 '16 at 06:40
  • @MukundGandlur There is no "user" as far as ORM is concerned. If you want to take the web site users' (via django-auth) timezones into account, you must write a view that sends the correct datetime to the helper method. – Selcuk Jun 03 '16 at 07:15
  • 1
    My settings are `USE_TZ = True, TIME_ZONE = 'UTC'.` But when I use `timezone.now()` it doesn't show `tzinfo=`.... So this datetime object is passed as naive one. Why does it happen? – user3595632 May 09 '17 at 06:21
  • 1
    @user3595632 Yes, `strptime` doesn't return timezone aware datetimes. See [this question](http://stackoverflow.com/questions/3305413/python-strptime-and-timezones). – Selcuk May 10 '17 at 03:22