简体   繁体   English

Django 2.0中的反向URL

[英]Reverse URL in Django 2.0

The new Django 2.0 update broke my way of reversing url and printing it to the template. 新的Django 2.0更新打破了我反转网址并将其打印到模板的方式。 Using regular expression, it would work fine but when using the new simplified way, it returns an error. 使用正则表达式可以很好地工作,但是当使用新的简化方法时,它将返回错误。

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

Here is what I use to print the url, 这是我用来打印网址的内容,

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

Here is the url pattern, 这是网址格式

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

and here is the article function, 这是文章功能,

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)

I haven't found a solution to this yet. 我还没有找到解决方案。 Hopefully this post will help others. 希望这篇文章对其他人有帮助。

In Django 2.0, url() is an alias for re_path() and still uses regular expressions. 在Django 2.0中, url()re_path()的别名,并且仍使用正则表达式。

Use path() for the simplified syntax. 使用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