提问人:Alejandroid 提问时间:4/19/2018 最后编辑:Alejandroid 更新时间:11/23/2020 访问量:1870
根据 django 项目中的用户更改时区
Change time zone depending on the user in django project
问:
我正在尝试更改项目中的时区,具体取决于用户选择的内容。
为此,我的数据库中有一个字段,我在其中保存所有可能的位置:
timezone = models.CharField(max_length=40, null=True, blank=True, choices=[(n,n) for n in pytz.all_timezones])
但问题是,当我尝试更改时区时,它不起作用。
---- setting.py ----
USE_TZ = True
TIME_ZONE = 'Europe/Madrid'
---- Dashboard (view.py) ---->输出
@login_required
def dashboard(request):
from datetime import datetime, timedelta
import pytz
print "Normal:" + str(datetime.now()) # Normal:2018-04-19 08:39:51.484283
print "TimeZone:" + str(timezone.now()) # TimeZone:2018-04-19 06:39:51.484458+00:00
u = User.objects.get(user=request.user) # u: Alejandroid
timezone_selected = u.timezone # timezone_selected: u'Canada/Saskatchewan'
timezone.activate(pytz.timezone(timezone_selected))
print "Normal:" + str(datetime.now()) # Normal:2018-04-19 08:40:02.829441
print "TimeZone:" + str(timezone.now()) # TimeZone:2018-04-19 06:40:04.329379+00:00
如您所见,它仅返回以 TIME_ZONE 和 UTC 时间定义的本地时间。
我正在使用 Django 1.8
我该如何让它工作?
谢谢。
我的解决方案
您需要创建一个中间件。
class TimezoneMiddleware(object):
def process_request(self, request):
from django.utils import timezone
import pytz
from settings import TIME_ZONE
if request.user.is_authenticated():
timezone_selected = request.user.timezone
if not timezone_selected:
timezone_selected = TIME_ZONE
timezone.activate(pytz.timezone(timezone_selected))
else:
timezone.deactivate()
答:
0赞
user10997436
11/23/2020
#1
Django 设置假设你将使用 datatime:
从 datetime 导入 datetime
日期时间.now()
或
datetime.now().strftime(“%Y/%m/%d %H:%M”)
只需使用这些函数来代替 timezone.now()
并在 settings.py 中添加:
USE_TZ = 真 TIME_ZONE = 'UTC' # UTC == 马德里/欧洲
评论