Antonio José
Antonio José

Reputation: 495

Working with timezone in Django - Best Practices

I would like your opinion about the practices I am using to deal with timezone, as shown below. Is correct? Should I worry about any more details?

Each client/user of the system is located in a region with different time, so I put in the model the record that identifies the region:

In model:

TIMEZONES = tuple(zip(pytz.all_timezones, pytz.all_timezones))
timezone = models.CharField (
    null = False,
    blank = False,
    max_length = 32,
    choices = TIMEZONES,
    default = 'UTC',
    verbose_name = "timezone",
    help_text = "Timezone"
)

When the user logs in, the settings.py TIME_ZONE variable changes according to the logged-in user's timezone:

At login:

from django.conf import settings
settings.TIME_ZONE = timezone

When I do a cursor query, I timezone as it is in settings.py:

In the query:

from django.conf import settings
timezone = settings.TIME_ZONE
query = "" "
    SET TIMEZONE = '{}';
    ...
"" ".format (timezone)

In templates, I enable timezone:

In the templates:

...
{% load tz%}
...
{% localtime on%}
...
{% endlocaltime%}

I hope I was clear in the presentation above. If you need more details, I can provide.

Thanks for sharing your experiences.

Upvotes: 1

Views: 720

Answers (1)

LuisSolis
LuisSolis

Reputation: 538

The ideal would be to use middleware to determine the user's time zone and save it in the session.

Django provides time zone selection functions. Use them to build the time zone selection logic that makes sense for you.

this answer is short because the correct answer is in Django documentation

https://docs.djangoproject.com/en/3.0/topics/i18n/timezones/#selecting-the-current-time-zone

Upvotes: 1

Related Questions