我已经关注了Django网站上的时区文档而没有运气。我的问题是我的模板上有一个选择框,应该填充pytz提供的常用时区,但无论出于何种原因,它都是空的。
我的最终目标是允许用户选择自己的时区。
提前感谢任何帮助。
view.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})
leads.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>
settings.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)
答案 0 :(得分:0)
我认为你可能会提出一个NameError或者其他东西。尝试导入pytz:
来自pytz import common_timezones
...
...
return render(request,'n2w / leads.html',{'timezones':common_timezones})
答案 1 :(得分:0)
从2.7.1升级我的Python安装后 - &gt; 2.7.3,我能够完美地导入pytz。谢谢你的帮助!