Django:sitemap.xml 和“未知时区”
Django 站点地图在以前的服务器上工作正常,在我的开发环境中工作正常,但在新服务器上的生产中出现故障,并显示:
ValidationError: [u'Unknown timezone'] (下面回溯)。当我尝试从管理员访问我们的模型之一时,我也遇到了类似的错误。
更新:
回溯中的路径 build/bdist.linux-x86_64/egg/timezones 提示我发生了一些奇怪的路径问题。事实证明,有人从另一台服务器复制了一堆东西,而不是进行正确的 pip 安装。我删除了一些旧的库,修复了 virtualenv 默认路径,并 pip 安装了 django-timezones。现在一切都运转良好。留下这个以防对其他人有帮助。
站点地图文档没有提及任何有关时区配置或依赖项的内容: https://docs.djangoproject.com/en/dev/ref/contrib/ sitemaps/
服务器的时区已正确设置为 America/Los_Angeles,并且我已在 settings.py 中设置了相同的时区,我不确定这里还可以查看什么,Google 没有显示任何内容。
我在 urls.py 的 SiteMaps 定义中引用了 8 个模型,但只有一个 BlogSiteMap 导致了损坏(如果我将其注释掉,则损坏停止,但我的站点地图中没有博客文章。它包括
class BlogSitemap(Sitemap):
changefreq = "weekly"
priority = 0.7
def items(self):
return Post.objects.filter(status=2).order_by('-modified')
def lastmod(self, obj):
return obj.modified
:模型是这样的(为简洁起见略有编辑)
class Post(models.Model):
"""Post model."""
title = models.CharField(_('title'), max_length=200)
slug = models.SlugField(_('slug'), unique_for_date='publish')
author = models.ForeignKey(User, blank=True, null=True)
body = models.TextField(_('body'))
tease = models.TextField(_('tease'), blank=True)
status = models.IntegerField(_('status'), choices=STATUS_CHOICES, default=2)
allow_comments = models.BooleanField(_('allow comments'), default=True)
fp_show = models.BooleanField('Show on homepage',default=False)
order = models.IntegerField(blank=True, null=True)
publish = models.DateTimeField(_('publish'),default=datetime.now())
created = models.DateTimeField(_('created'), auto_now_add=True)
modified = models.DateTimeField(_('modified'), auto_now=True)
categories = models.ManyToManyField(Category, blank=True)
tags = TagField()
objects = PublicManager()
def __unicode__(self):
return u'%s' % self.title
@permalink
def get_absolute_url(self):
return ('blog_detail', None, {
'year': self.publish.year,
'month': self.publish.strftime('%b').lower(),
'day': self.publish.day,
'slug': self.slug
})
使用: 姜戈1.3 Python 2.7 RHEL 5.7
谢谢。
Traceback (most recent call last):
File "/home/username/virtualenvs/kdmc/lib/python2.7/site-packages/django/core/handlers/base.py", line 111, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/home/username/virtualenvs/kdmc/lib/python2.7/site-packages/django/contrib/sitemaps/views.py", line 39, in sitemap
urls.extend(site().get_urls(page=page, site=current_site))
File "/home/username/virtualenvs/kdmc/lib/python2.7/site-packages/django/contrib/sitemaps/__init__.py", line 75, in get_urls
for item in self.paginator.page(page).object_list:
File "/home/username/virtualenvs/kdmc/lib/python2.7/site-packages/django/db/models/query.py", line 107, in _result_iter
self._fill_cache()
File "/home/username/virtualenvs/kdmc/lib/python2.7/site-packages/django/db/models/query.py", line 772, in _fill_cache
self._result_cache.append(self._iter.next())
File "/home/username/virtualenvs/kdmc/lib/python2.7/site-packages/django/db/models/query.py", line 286, in iterator
obj = model(*row[index_start:aggregate_start])
File "/home/username/virtualenvs/kdmc/lib/python2.7/site-packages/django/db/models/base.py", line 297, in __init__
setattr(self, field.attname, val)
File "/home/username/virtualenvs/kdmc/lib/python2.7/site-packages/django/db/models/fields/subclassing.py", line 99, in __set__
obj.__dict__[self.field.name] = self.field.to_python(value)
File "build/bdist.linux-x86_64/egg/timezones/fields.py", line 43, in to_python
return coerce_timezone_value(value)
File "build/bdist.linux-x86_64/egg/timezones/utils.py", line 34, in coerce_timezone_value
raise ValidationError("Unknown timezone")
ValidationError: [u'Unknown timezone']
Django sitemaps worked fine on a previous server, and work fine in my development environment, but break in production on a new server, with:
ValidationError: [u'Unknown timezone']
(traceback below). I was also getting a similar error when trying to access one of our models from admin.
Update:
The path build/bdist.linux-x86_64/egg/timezones in the traceback tipped me off that there was some weird path stuff going on. Turned out someone had copied a bunch of stuff from another server rather than doing proper pip installs. I removed some old libs, fixed a virtualenv default path, and pip installed django-timezones. All working nicely now. Leaving this in case it's helpful to anyone else.
The sitemap docs don't mention anything about timezone configuration or dependencies:
https://docs.djangoproject.com/en/dev/ref/contrib/sitemaps/
The server's timezone is correctly set to America/Los_Angeles, and I've set the same in settings.py I'm not sure what else to look at here and Google's turning up nothing.
I reference 8 models in my SiteMaps definition in urls.py but only one BlogSiteMap is causing the breakage (if I comment it out the breakage stops, but then I don't have blog posts in the sitemap. It consists of:
class BlogSitemap(Sitemap):
changefreq = "weekly"
priority = 0.7
def items(self):
return Post.objects.filter(status=2).order_by('-modified')
def lastmod(self, obj):
return obj.modified
The blog Post model is this (edited slightly for brevity)
class Post(models.Model):
"""Post model."""
title = models.CharField(_('title'), max_length=200)
slug = models.SlugField(_('slug'), unique_for_date='publish')
author = models.ForeignKey(User, blank=True, null=True)
body = models.TextField(_('body'))
tease = models.TextField(_('tease'), blank=True)
status = models.IntegerField(_('status'), choices=STATUS_CHOICES, default=2)
allow_comments = models.BooleanField(_('allow comments'), default=True)
fp_show = models.BooleanField('Show on homepage',default=False)
order = models.IntegerField(blank=True, null=True)
publish = models.DateTimeField(_('publish'),default=datetime.now())
created = models.DateTimeField(_('created'), auto_now_add=True)
modified = models.DateTimeField(_('modified'), auto_now=True)
categories = models.ManyToManyField(Category, blank=True)
tags = TagField()
objects = PublicManager()
def __unicode__(self):
return u'%s' % self.title
@permalink
def get_absolute_url(self):
return ('blog_detail', None, {
'year': self.publish.year,
'month': self.publish.strftime('%b').lower(),
'day': self.publish.day,
'slug': self.slug
})
Using:
Django 1.3
Python 2.7
RHEL 5.7
Thanks.
Traceback (most recent call last):
File "/home/username/virtualenvs/kdmc/lib/python2.7/site-packages/django/core/handlers/base.py", line 111, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/home/username/virtualenvs/kdmc/lib/python2.7/site-packages/django/contrib/sitemaps/views.py", line 39, in sitemap
urls.extend(site().get_urls(page=page, site=current_site))
File "/home/username/virtualenvs/kdmc/lib/python2.7/site-packages/django/contrib/sitemaps/__init__.py", line 75, in get_urls
for item in self.paginator.page(page).object_list:
File "/home/username/virtualenvs/kdmc/lib/python2.7/site-packages/django/db/models/query.py", line 107, in _result_iter
self._fill_cache()
File "/home/username/virtualenvs/kdmc/lib/python2.7/site-packages/django/db/models/query.py", line 772, in _fill_cache
self._result_cache.append(self._iter.next())
File "/home/username/virtualenvs/kdmc/lib/python2.7/site-packages/django/db/models/query.py", line 286, in iterator
obj = model(*row[index_start:aggregate_start])
File "/home/username/virtualenvs/kdmc/lib/python2.7/site-packages/django/db/models/base.py", line 297, in __init__
setattr(self, field.attname, val)
File "/home/username/virtualenvs/kdmc/lib/python2.7/site-packages/django/db/models/fields/subclassing.py", line 99, in __set__
obj.__dict__[self.field.name] = self.field.to_python(value)
File "build/bdist.linux-x86_64/egg/timezones/fields.py", line 43, in to_python
return coerce_timezone_value(value)
File "build/bdist.linux-x86_64/egg/timezones/utils.py", line 34, in coerce_timezone_value
raise ValidationError("Unknown timezone")
ValidationError: [u'Unknown timezone']
请参阅更新:上面的部分 - 事实证明,这是由旧安装的库和 virtualenv 中不正确的路径引起的一系列冲突。
See Update: section above - this turned out to be a series of conflicts arising from old installed libraries and an incorrect path in the virtualenv.