模板中博客文章的反向 url

reverse url of the blog article in template

{% url 'article' article.get_absolute_url %} 不会按预期工作。收到错误 NoReverseMatch at /blog/

Url 模式是:

url(r'^/(?P<slug>[-\w]+)-(?P<id>[-\d]+)/$', article, name='article'), 其中 article 是函数名称。

它是:

{% url 'article' article.slug article.pk %}

{{ article.get_absolute_url }}

后者只有在你的模型中有这样的东西时才有效:

class Article(models.Model):
     slug = models.SlugField()
     ...
     def get_absolute_url(self):
         return reverse('article', args=[self.slug, self.pk])