2

新的 Django 2.0 更新打破了我反转 url 并将其打印到模板的方式。使用正则表达式,它可以正常工作,但是当使用新的简化方式时,它会返回错误。

NoReverseMatch at /blog/archive/
Reverse for 'article' with keyword arguments '{'id': 1}' not found. 1 pattern(s) tried: ['blog/article/<int:id>/$']

这是我用来打印网址的内容,

<h3 class="item-title"><a href="{% url 'blog:article' id=article.id %}">{{ article.title }}</a></h3>

这是网址格式,

    url(r'^blog/article/<int:id>/$', views.article, name='article'),

这是文章功能,

def article(request, id):
    try:
        article = Article.objects.get(id=id)
    except ObjectDoesNotExist:
        article = None

    context = {
        'article': article,
        'error': None,
    }

    if not article:
        context['error'] = 'Oops! It seems that the article you requested does not exist!'

    return render(request, 'blog/article.html', context)

我还没有找到解决这个问题的方法。希望这篇文章能帮助其他人。

4

1 回答 1

3

在 Django 2.0 中,url()它是正则表达式的别名,re_path()并且仍然使用正则表达式。

用于path()简化语法。

from django.urls import path

urlpatterns = [
    path(r'^blog/article/<int:id>/$', views.article, name='article'),
]
于 2017-12-05T15:08:58.657 回答