我是Django的新手,我正在尝试一个单独的页面,我可以查看单个文章。目前我有:
#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 /”错误。我做错了什么?
编辑:除了为答案建议的更改之外,还有一个拼写错误导致问题。但是,它不会影响下面的答案。
答案 0 :(得分:1)
首先,您不应该在模板中生成此网址。您应该在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>