1

我想允许用户更改时区。我已阅读并遵循文档

我可以看到下拉列表,我可以选择不同的时区并单击设置。一切都设置好了,但它没有效果。它仍将欧洲/伦敦显示为页面上的时区。我可能错过了什么?

我的中间件:

from django.utils import timezone

class TimezoneMiddleware(object):
    def process_request(self, request):
        tz = request.session.get('django_timezone')
        if tz:
            timezone.activate(tz)

网址:

(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
4

1 回答 1

0
request.session.session_key

应该替换为

'django_timezone'
于 2012-08-30T12:00:57.063 回答