2017-04-07 46 views
1

我運行Django的服務器,而無需任何代理:如何在http響應(django服務器)中更改時區?

python manage.py runserver 0.0.0.0:80 

設置我的本地時區的Linux服務器上,它是正確的:

[email protected]:/app# date 
Fri Apr 7 12:38:42 MSK 2017 

我設立本地時區在我的Django的settings.py項目:

TIME_ZONE = 'Europe/Moscow' 

,並檢查它:

>>> from django.utils.timezone import localtime, now 
>>> localtime(now()) 
datetime.datetime(2017, 4, 7, 12, 38, 42, 196476, 
tzinfo=<DstTzInfo 'Europe/Moscow' MSK+3:00:00 STD>) 

但是當我打開任何網頁從客戶(谷歌Chrome瀏覽器) - 在HTTP響應頭時區不在本地:

Date:Fri, 07 Apr 2017 09:38:42 GMT 

我如何更改HTTP頭時區的全球所有項目?

回答

0

我怎樣才能改變HTTP頭時區的全球所有項目?

HTTP日期頭是defined在UTC是(用字符GMT表示由於歷史的原因),所以既不Django的或任何其他的服務器或框架將允許你將它們定位到您的時區。你有這樣的理由嗎?

Django確實有辦法切換到本地時區(請參閱activate()),但這隻適用於特定於應用程序的內容,而不適用於HTTP標頭。

+0

謝謝,沒有理由將它們本地化。我只想知道他們爲什麼使用UTC。您的答案和IETF參考幫助。 – xtdwps

1

使用pytz,作爲astimezone方法

from pytz import timezone 

time_zone = timezone(settings.TIME_ZONE) 
currentTime = currentTime.astimezone(time_zone) 

在你的中間件:

import pytz 

from django.utils import timezone 
from django.utils.deprecation import MiddlewareMixin 

class TimezoneMiddleware(MiddlewareMixin): 
    def process_request(self, request): 
     tzname = request.session.get('django_timezone') 
     if tzname: 
      timezone.activate(pytz.timezone(tzname)) 
     else: 
      timezone.deactivate() 

在你view.py

from django.shortcuts import redirect, render 

def set_timezone(request): 
    if request.method == 'POST': 
     request.session['django_timezone'] = request.POST['timezone'] 
     return redirect('/') 
    else: 
     return render(request, 'template.html', {'timezones': pytz.common_timezones}) 

在你templete.html

{% load tz %} 
{% get_current_timezone as TIME_ZONE %} 
<form action="{% url 'set_timezone' %}" method="POST"> 
    {% csrf_token %} 
    <label for="timezone">Time zone:</label> 
    <select name="timezone"> 
     {% for tz in timezones %} 
     <option value="{{ tz }}"{% if tz == TIME_ZONE %} selected="selected"{% endif %}>{{ tz }}</option> 
     {% endfor %} 
    </select> 
    <input type="submit" value="Set" /> 
</form> 
+0

我應該把這個代碼放在哪裏?什麼是在賦值中引用的currentTime變量? – xtdwps

+0

@xtdwps:我已經更新了答案請看看 – Surajano

+0

官方Django文檔的鏈接:https://docs.djangoproject.com/en/2.0/topics/i18n/timezones/ –

相關問題