ng150716
ng150716

Reputation: 2244

Django: DateTimeField received a naive datetime

I am working on creating a view that will only display posts whose deadlines dates have not passed. accomplish this I've added the following my views.py file:

current_posts = Posts.objects.filter(post_name=post, deadline__range=[date.today(), "2999-12-31"]).order_by('deadline')

This way I am able to only show posts whose deadline range fall between today and December 31, 2999. However I get the following error, and no posts show at all:

RuntimeWarning: DateTimeField OfferedFunds.deadline received a naive datetime (2999-12-31 00:00:00) while time zone support is active.
  RuntimeWarning)

Past solutions posted left me trying the following which also does not work:

timezone.now()
current_posts = Posts.objects.filter(post_name=post, deadline__range=[timezone.now(), "2999-12-31"]).order_by('deadline')

What does work is if instead of entering: timezone.now(), I enter an actual date like "2015-10-10" however this defeats the purpose. Any ideas on how I can solve this?

Upvotes: 1

Views: 1735

Answers (3)

radtek
radtek

Reputation: 36270

In your settings.py set USE_TZ = False, so that should fix the warning. In my case I wanted to work with native datetime globally so that's what I ended up doing. Cheers!

Upvotes: 0

BallpointBen
BallpointBen

Reputation: 13750

Instead of checking a range, you can do deadline__gte=timezone.now()

This page has more info: https://docs.djangoproject.com/en/stable/ref/models/querysets/#gte

Upvotes: 3

chill_turner
chill_turner

Reputation: 519

I actually ran into this problem today at work! Basically the deadline__range=[date.today(), '2999-10-10'] line has a UTC aware time in the first slot and a UTC unaware time in the second slot. Let me guide you to the post that helped me How to make an unaware datetime timezone aware in python. There are some pure python solutions and some django solutions but I think you'll find what you need there!

Upvotes: 0

Related Questions