刚开始使用 Django,但遇到了一些困难——我决定尝试编写一个简单的博客引擎,同时参考 django-basic-apps 库。
在 blog/urls.py 中,我有这个条目按日期映射到实际的帖子,例如 blog/2009/aug/01/test-post
urlpatterns = patterns('',
url(r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{1,2})/(?P<slug>[-\w]+)/$', 'blog.views.post_detail'),
...
以及渲染帖子的视图:
def post_detail(request, slug, year, month, day, **kwargs):
return date_based.object_detail(
request,
year = year,
month = month,
day = day,
date_field = 'created_at',
slug = slug,
queryset = Content.objects.filter(published=True),
**kwargs
)
在我实现的模型get_absolute_url
中,我可以在主博客页面上单击帖子标题来查看它:
class Content(models.Model):
...
@permalink
def get_absolute_url(self):
return ('blog.views.post_detail', (), {
'slug': self.slug,
'year': self.created_at.year,
'month': self.created_at.strftime('%b').lower(),
'day': self.created_at.day
})
最后,在主页的帖子列表中,应该在标题中插入永久链接:
{% for content in object_list %}
<div class="content_list">
<h3 class="content_title"><a href="{{ content.get_absolute_url }}">{{ content.title }}</a></h3>
<p class="content_date">{{ content.published_at|date:"Y F d"}}</p>
<p class="content_body">{{ content.body }}</p>
<p class="content_footer">updated by {{ content.author }} at {{ content.updated_at|timesince }} ago</p>
</div>
{% endfor %}
但是链接显示为空,当我尝试content.get_absolute_url()
从 django shell 调用时,会抛出错误:
NoReverseMatch: Reverse for '<function post_detail at 0xa3d59cc>' with arguments '()' and keyword arguments '{'year': 2009, 'slug': u'another_test', 'day': 15, 'month': 'aug'}' not found.
编辑:原来这是一个 Python 命名空间问题(见下文)。但无论如何,我上面显示的urls.py不正确吗?