繁体   English   中英

Django 2.0中的反向URL

[英]Reverse URL in Django 2.0

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

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)

我还没有找到解决方案。 希望这篇文章对其他人有帮助。

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

使用path()简化语法。

from django.urls import path

urlpatterns = [
    path(r'^blog/article/<int:id>/$', views.article, name='article'),
]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM