Search code examples
djangodjango-modelsdjango-templatestimezone

Applying local timezone in Django templates


I use Django 3.1.7 and postgreSQL for the database.

So here is the problem, after saving a date in my database I try to display it in a template with the timezone of the visitor and it's still displaying me the date UTC.

I have these values in my settings.py:

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

my model:

class Log(models.Model):
    user = models.ForeignKey(to=User, on_delete=models.PROTECT)
    log = models.CharField(max_length=255)
    type = models.CharField(max_length=50)
    date = models.DateTimeField(auto_now_add=True)
    company = models.ForeignKey(to=Company, on_delete=models.PROTECT)

my context processor getting me the objects:

def logs_processor(request):
    if request.user.has_perm('loging.can_see_logs'):
        try:
            logs = Log.objects.filter(company=request.user.company).order_by('-date')[:50]
        except TypeError:
            logs = None
        return {'side_logs': logs}
    else:
        return {'side_logs': []}

And my template:

{% load tz %}
{% for log in side_logs %}
   {{ log.date|localtime }}
{% endfor %}

I tried without the |localtime but no luck.

When I specify by hand the TZ like log.date|timezone:"Europe/Paris" That works well.

As well I precise that I have pytz installed.

Here what my dates look like in the database (it seams they are not naive and placed on UTC as planed): 2021-03-10 04:10:11.849048 +00:00

Any idea?


Solution

  • The documentation for the localtime filter says that it "enables or disables conversion of aware datetime objects to the current time zone". The current time zone is defined as the one that was explicitly set by calling activate() or, failing that, is the value of the TIME_ZONE setting.

    You're not calling activate(), and the value of the TIME_ZONE setting is UTC, so that's why you're seeing the values in UTC.

    If your goal is to use the "timezone of the visitor" you're going to have to do more work, because there's no way for the server to automatically know what time zone the user wants to use. The documentation discusses this, and gives some examples of how you might do it.