我想允许用户更改时区。我已阅读并遵循documentation
我可以看到下拉列表,我可以选择不同的时区并点击设置。一切都准备好了,但没有效果。它仍然显示欧洲/伦敦作为页面上的时区。 我可以错过什么?
我的中间件:
from django.utils import timezone
class TimezoneMiddleware(object):
def process_request(self, request):
tz = request.session.get('django_timezone')
if tz:
timezone.activate(tz)
URL:
(r'^timezone/', set_timezone),
(r'^$', main_page_view),
查看:
def set_timezone(request):
if request.method == 'POST':
request.session[request.session.session_key] = pytz.timezone(request.POST['timezone'])
return redirect(request.path)
else:
return redirect('/') #Thats quite annoying that I have to redirect it afterwards, how can I stay on the same page?
def main_page_view(request):
...
variables = {'timezones': pytz.common_timezones}
return render(request, 'main_page.html', variables)
base.html文件
{% load tz %}{% load url from future %}
<form action="/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>
Main_page.html
{% load tz %}
{% get_current_timezone as TIME_ZONE %}
{{TIME_ZONE}}
设置:
TIME_ZONE = 'Europe/London'
USE_TZ = True
答案 0 :(得分:0)
request.session.session_key
应替换为
'django_timezone'