django 1.4 如何从客户端自动获取用户的时区

2022-01-16 00:00:00 python django timezone

问题描述

我想知道是否有办法从客户端自动检索用户的时区.尤其是在登录时.

I would like to know if there is a way to automatically retrieve user's timezone from client. Especially during login.

我尝试在登录页面中添加这个(使用 auth.login):

I tried to add this in the login page (using auth.login):

{% get_current_timezone as TIME_ZONE %}

然后将其添加到登录表单中

and then add this in the login form

<input type="hidden" name="next" value="/redirect/?tz={{ TIME_ZONE }}">

tz 始终是服务器的时区.

but tz is always the timezone of the server.


解决方案

来自 文档:

选择当前时区

当前时区是相当于翻译的当前语言环境.然而,没有相当于 Django 可以使用的 Accept-Language HTTP 标头自动确定用户的时区.相反,Django 提供时区选择功能.使用它们来构建时区对您有意义的选择逻辑.

The current time zone is the equivalent of the current locale for translations. However, there's no equivalent of the Accept-Language HTTP header that Django could use to determine the user's time zone automatically. Instead, Django provides time zone selection functions. Use them to build the time zone selection logic that makes sense for you.

您可以尝试使用 getTimezoneOffset 功能或尝试做一些 geoip 魔术并按位置计算时区.可能最可靠的方法是直接询问用户并将此信息保存在用户配置文件/会话中.

You can try setting timezone cookie via javascript by utilizing getTimezoneOffset function or try to do some geoip magic and figure timezone by location. Probably the most reliable way would be to ask the user directly and save this information in user profile/session.

相关文章