Arafat Khan
Arafat Khan

Reputation: 857

Django templates do not respect DateTimes in different timezone

In my Django app, I am storing all the DateTime objects as aware objects in UTC. But my users may live in different parts of the world. So, I have set up a form for them to choose their respective time zone. In the backend, I have written Python code to first convert the corresponding DateTime objects to the local time zone using Django's astimezone() function. There is an attribute under the user's profile model that stores the timezone. So, all my code will actually do operations based on the user's local time while in the actual database they are stored as UTC. Now, I seem to have come across a problem and I can't see the reason why this should occur. In the app, I have made a dedicated page to show the users a comparison of the server time and their local time. This is my code

view function that renders that page

def check_time(request):
    " A view function that let's user view their local time and server time (usually UTC) at a glance"
    user = User.objects.get(username=request.user.username)

    server_time = timezone.now()
    user_localtime = server_time.astimezone(user.profile.timezone)

    context = {
        "server_time": server_time,
        "user_localtime": user_localtime
    }

    return render(request, "ToDo/check_time.html", context=context)

check_time.html

{% extends "ToDo/base.html" %}
{% load static %}
{% block content %}

<div class="content-section dark-mode-assist-section">
    <h1>Check if your local time is accurate</h1>
    <br><br>
    <h2>Server time: {{ server_time }}</h2>
    <h2>Your time: {{ user_localtime }}</h2>
</div>


{% endblock content %}

This is what happens: enter image description here

Both of the times are the same. Although I had converted the time before passing it to the template. Why does this error occur?

Additional info:

Upvotes: 2

Views: 555

Answers (1)

AzyCrw4282
AzyCrw4282

Reputation: 7744

Given your last comment that the astimezone() is working correctly in your views.py it seems like the error is happening in the templates. Most likely that it converts all time to UTC time as may be specified in your settings.py with TIME_ZONE.

You can enable or disable the conversion of datetime objects using templates tags:

{% load tz %}

{% localtime on %}
    {{ value }}
{% endlocaltime %}

{% localtime off %}
    {{ value }}
{% endlocaltime %} 

You can also set TIME_ZONE and USE_TZ in settings.py to get around this issue.

Upvotes: 1

Related Questions