inquilabee
inquilabee

Reputation: 791

Django Timezone unaware DateTimeField Error

I have a simple Post model in my blog app as follows:

class Post(CreateUpdateDateModel):
    # ...
    body = models.TextField()
    publish = models.DateTimeField()
    # ...

    def get_absolute_url(self):
        print(self.publish) # printing publish date
        return reverse(
            'blog:post_detail',
            args=(
                self.publish.year,
                self.publish.month,
                self.publish.day,
                self.slug
            )
        )

In my settings.py, I have:

TIME_ZONE = 'Asia/Kolkata'

USE_TZ = True

I am using Django Admin to creat Post instances. Django Admin shows/displays correct time (local time, March 10). Printing of publish date in get_absolute_url method displays 2018-03-09 19:54:29+00:00 (March 9). This leads to generation of incorrect url causing errors when a post is accessed: DoesNotExist at /blog/2018/3/9/third-blog-normal/

Please help or provide hints to resolve this issue.

Upvotes: 1

Views: 379

Answers (1)

Brian
Brian

Reputation: 7654

To generate absolute URLs based on the server's local time, the time that is fed into get_absolute_url() will simply have to be in its local timezone:

from django.utils.timezone import localtime

class Post(CreateUpdateDateModel):
    # ...
    body = models.TextField()
    publish = models.DateTimeField()
    # ...

    def get_absolute_url(self):
        local_publish = localtime(self.publish)
        return reverse(
            'blog:post_detail',
            args=(
                local_publish.year,
                local_publish.month,
                local_publish.day,
                self.slug
            )
        )

The real lesson here is, despite what their names suggest, setting USE_TZ and TIME_ZONE still saves your datetimes in UTC. Whenever Django retrieves a datetime from the database, it will lose its timezone.

Upvotes: 3

Related Questions