7

我想要实现的是:我的新闻应用程序应该显示一个 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.`
4

2 回答 2

3

Thanks @Daniel Roseman and @yuvi. With your help I managed to solve my problem by defining the URL pattern to this:

r'^(?P<pk>\d+)(?:/(?P<slug>[\w\d-]+))?/$',

Which allows all my wanted forms of

  • news/nn
  • news/nn/
  • news/nn/a-slug
  • news/nn/a-slug/

In the template, I use

{% url 'news_detail' news.id news.prettyurl %}

Which shows the fourth version in the listing above.

Thanks again!

于 2014-02-18T20:13:45.330 回答
1

我不太清楚你为什么要费心去捕捉蛞蝓。与其在 URL 模式中使用命名组,不如使用一个忽略 PK 之后的所有内容的组:

r'^(?P<pk>\d+)/.*',

无论您是否通过了蛞蝓,这同样有效,因此您可以摆脱重复的模式。

但是,您所拥有的存在两个基本问题。首先,即使您声明您只想在 PK 上实际匹配,您甚至不会将 PK 传递给 URL,而只是传递 slug。其次,即使是 slug 似乎也是空白的,因为错误消息指出( args 变量只是'')。

您应该改为传递实际的 PK:

{% url 'news_detail' news.pk %}
于 2014-02-17T17:05:13.160 回答