pythonpython-3.xdjangopython-2.7runtime-error

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


I am trying to test a cart creation based on django cart. But I have the following warning 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 front.cart import models
import datetime
from django.utils import timezone

def create_cart_in_database():
    cart = models.Cart()
    cart.creationDate = datetime.datetime.now()
    cart.save()

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():
    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 related to datetime format?

  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

Solution

  • 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