2015-11-06 17 views
0

我是Django的新手,我正在嘗試建立一個單獨的頁面,可以查看單個文章。目前,我有:如何使用DateDetailView和slu to呈現單個文章的頁面?

#views.py 
class ArticleView(DateDetailView): 
    template_name = 'blog/article.html' 
    model = Article 
    date_field = "pub_date" 
    #I am not sure which one to use 
    slug_field = "unique_url_suffix" 
    slug_url_kwarg = 'unique_url_suffix' 

#urls.py 
urlpatterns = [ 
url(r'^(index\.html)?$',views.IndexView.as_view(),name='index'), 
url(r'^(?P<year>[0-9]{4})/(?P<month>[-\w]+)/(?P<day>[0-9]+)/(?P<slug>[-\w]+)/$', 
views.ArticleView.as_view(), 
name="article_detail"), 
] 

index.html對象從Article類循環中:

<h2><a href= "{% url 'blog:article_detail' article %}">{{article.title}}</a></h2> 

我也曾嘗試手動輸入的參數,像這樣:

<h2><a href= "{% url 'blog:article_detail' date_field=article.pub_date slug=article.unique_url_suffix %}">{{article.title}}</a></h2> 

我不斷收到「NoReverseMatch at/blog /」錯誤。我做錯了什麼?

編輯:除了建議的答案更改之外,還有一個錯誤導致的問題。不過,這並不影響下面的答案。

回答

1

首先,您不應該在模板中生成此URL。你應該定義你的Article模型get_absolute_url方法,看起來像這樣:

from django.core.urlresolvers import reverse 

def get_absolute_url(self): 
    # Note - you have to supply each of the date components separately 
    # because you need to match the URL regex. 
    return reverse (
     'blog:article_detail', 
     kwargs={'year': self.pub_date.strftime("%Y"), 'month': self.pub_date.strftime("%b"), 
     'day': self.pub_date.strftime("%d"), 'slug': self.unique_url_suffix} 
    ) 

,然後在模板:

<h2><a href= "{{ article.get_absolute_url }}">{{article.title}}</a></h2> 
+0

我做了這些變化,但我得到一個屬性錯誤,說, '通用細節視圖ArticleView必須用對象pk或者slug來調用。' 是否應該更新/覆蓋views.py中的某些內容,比如get_object()方法? –

+0

沒關係。在slug字段的'ArticleView'類中有一個拼寫錯誤。問題已經解決,這看起來像一個更清潔的組織方式。想。 –