我在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>
设置.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)
我认为您可能引发了NameError之类的问题。尝试导入pytz:
从pytz导入common_timezones
return render(request,'n2w/leads.html',{'timezones':common_timezones})
从2.7.1->2.7.3升级我的Python安装后,我能够完美地导入pytz。谢谢你的帮助!