I have a Django (v1.10.6) project that has some models with datetime fields, for example:
created_at = models.DateTimeField(auto_now_add=True)
that are stored in PostgreSQL database without timezone information:
created_at timestamp without time zone NOT NULL
postgresql.conf
:
timezone = 'UTC'
I want all the dates of my application to be shown in America/Bogota
time zone (it shouldn't depend on user's actual time zone), so my settings.py
file has the following configuration:
TIME_ZONE = 'America/Bogota'
USE_I18N = False
USE_L10N = True
USE_TZ = True
SHORT_DATETIME_FORMAT = 'd-m-Y H:i:s'
SHORT_DATE_FORMAT = 'd-m-Y'
TIME_FORMAT = 'H:i:s'
but when I write
{{ object.created_at|date:'SHORT_DATETIME_FORMAT' }}
in templates, it still shows the date in UTC
format.
Update:
I added the following middleware, but it didn't help:
class TimezoneMiddleware(MiddlewareMixin):
def process_request(self, request):
timezone.activate(pytz.timezone(settings.TIME_ZONE))
Update 2:
It works the following way:
import pytz
from django.utils import timezone
timezone.is_naive(object.created_at) # True
object.created_at.replace(tzinfo=timezone.utc)
(forcing the date to be in UTC
timezone and then passing it to template without localize
filter) but I don't understand why Django still returns naive datetime when USE_TZ
is set to True
.