Khr*_*dal 9 python django timezone django-settings django-timezone
我试图让我的 Django 应用程序与当前用户的时区一起工作,但我没有得到任何结果......
在我的 settings.py 文件中我设置:
TIME_ZONE = 'UTC'
Run Code Online (Sandbox Code Playgroud)
在我的中views.py,我在代码顶部设置:
activate(settings.TIME_ZONE)
Run Code Online (Sandbox Code Playgroud)
但这不起作用,在创建帖子时,正在获取我的最后一个时区“马德里”,而不是我当前的时区。
有办法让这项工作发挥作用吗?
谢谢你!
小智 16
我希望这可以帮助别人。由于Django无法自动检测用户的时区是什么,因此我想到了在登陆页面上用JS将用户的时区保存在cookie中。
放置在base.html中
<script>
// Timezone settings
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone; // e.g. "America/New_York"
document.cookie = "django_timezone=" + timezone;
</script>
Run Code Online (Sandbox Code Playgroud)
我按照 Django 官方文档中指示的步骤进行了一些细微的修改。
import zoneinfo
from django.utils import timezone
class TimezoneMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
try:
# get django_timezone from cookie
tzname = request.COOKIES.get("django_timezone")
if tzname:
timezone.activate(zoneinfo.ZoneInfo(tzname))
else:
timezone.deactivate()
except Exception as e:
timezone.deactivate()
return self.get_response(request)
Run Code Online (Sandbox Code Playgroud)
oni*_*ght -4
来自https://docs.djangoproject.com/en/3.1/topics/i18n/timezones/
from django.utils import timezone
now = timezone.now()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14751 次 |
| 最近记录: |