我想要实现的是:我的新闻应用程序应该显示一个 slug,但只能通过 ID 以/news/24/this-is-the-slug的形式查询文章
不幸的是,我NoReverseMatch: Reverse for 'news_detail' with arguments '('',)' and keyword arguments '{}' not found.
在尝试浏览文章时遇到了问题。如上所述,模板中生成的 URL 看起来是正确的(我可以通过 Haystack 进行搜索来确认这一点,它提供了正确的 URL)。
模型.py
class News(models.Model):
id = models.IntegerField(primary_key=True, editable=False)
category = models.CharField(max_length=50L)
title = models.CharField(max_length=200L)
rss_summary = models.TextField(max_length=2000L)
body_text = models.TextField(max_length=5000L)
post_date = models.DateTimeField()
prettyurl = models.SlugField(max_length=100L)
class Meta:
db_table = 'news'
def __unicode__(self):
return self.title
def get_absolute_url(self):
return urlresolvers.reverse('news_detail', kwargs={'pk': self.id, 'slug': self.prettyurl })
网址.py
urlpatterns = patterns(
'',
url(
r'^$',
view=views.NewsListView.as_view(),
name='news_index'),
url(
r'^(?P<pk>\d+)/',
view=views.NewsDetailView.as_view(),
name='news_detail'),
url(
r'^(?P<pk>\d+)/(?P<slug>[-\w]+)/$',
view=views.NewsDetailView.as_view(),
name='news_detail'),
url(
r'^archive/$',
view=views.NewsArchiveIndexView.as_view(),
name="archive_month"),
[... more unrelated urls ...]
视图.py
class NewsDetailView(DetailView):
#name='news_detail'),
model = News
context_object_name = 'news'
#slug_url_kwarg = 'prettyurl'
#slug_field = 'prettyurl'
template_name = 'news/detail.html'
模板
`<p><a href="{% url 'news_detail' news.slug %}">Permalink</a> for this article.`