2009-09-12 81 views
2

剛開始使用Django,但碰到了一堵牆 - 我決定嘗試編寫一個簡單的博客引擎,同時引用django-basic-apps庫。Django新手 - NoReverseMatch錯誤

在blog/urls.py中,我有這個條目按日期映射到實際的帖子,例如,博客/ 2009/8/01 /測試後

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 %} 

但是鏈接顯示爲空,當我嘗試調用從Django的content.get_absolute_url()殼的錯誤被拋出:

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如上所示不正確?

回答

3

谷歌搜索其他新手Django教程,並得到了所有的URL到父文件夾urls.py,這似乎解決了這個問題的想法。 :)所以,最後,我的主要urls.py現在有:

from djangoblog.blog import views 
urlpatterns = patterns('', 

    (r'^blog/(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{1,2})/(?P<slug>[-\w]+)/$', 
    views.post_detail), 
    (r'^blog/(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{1,2})/$', 
    views.post_archive_day), 
    ... 

編輯:編輯:後休閒黑客第2天,我理解的URLconf + Django的意見好了很多了,還好。 :)我已經將模式移回到blog/urls.py中,取消了所有基於日期的自定義視圖,並從urls.py中調用它們,併爲需要@permalinked的項目命名模式。

urls.py名爲模式:

from blog import views 
... 
(r'(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{1,2})/(?P<slug>[-\w]+)/$', 
    'object_detail', dict(info_dict, slug_field='slug', month_format='%m'), 
    'post_detail'), 
... 
(r'category/(?P<slug>[-\w]+)/$', views.category_detail), 

models.py:

class Post: 
    @permalink 
    def get_absolute_url(self): 
    return ('post_detail',(), { 
        .... 

class Category: 
    @permalink 
def get_absolute_url(self): 
    return ('blog.views.category_detail',(), {'slug': self.slug})