我按照 Django 网站上的时区文档没有运气。我的问题是我的模板上有一个选择框,应该填充 pytz 提供的常用时区,但是,无论出于何种原因,它都是空的。
我的最终目标是允许用户选择自己的时区。
任何帮助表示赞赏,在此先感谢。
视图.py:
def set_timezone(request):
if request.method == 'POST':
request.session['django_timezone'] = pytz.timezone(request.POST['timezone'])
return redirect('/')
else:
return render(request, 'n2w/leads.html', {'timezones': pytz.common_timezones})
线索.html:
{% load tz %}
{{ datetime }}
<form action="" 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>
设置.py:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.timezone.TimeZoneMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
#'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'registration',
'django.contrib.humanize',
'n2w',
'n2api',
'dajaxice',
'pytz',
)
中间件类(timezone.py):
from django.utils import timezone
class TimeZoneMiddleware(object):
def process_request(self, request):
tz = request.session.get('django_timezone')
if tz:
timezone.activate(tz)