【问题标题】:Reverse URL in Django 2.0Django 2.0 中的反向 URL
【发布时间】:2018-05-19 07:12:40
【问题描述】:

新的 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)

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

【问题讨论】:

    标签: python django django-urls django-2.0


    【解决方案1】:

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

    使用path() 作为简化语法。

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

    【讨论】:

    • 谢谢亲爱的 sanger,我应该阅读更多关于更新的信息。好像他们改变了很多东西。我的网站现在可以运行了!
    猜你喜欢
    • 2015-01-07
    • 1970-01-01
    • 2019-01-12
    • 2010-11-16
    • 2023-03-25
    • 2019-11-04
    • 1970-01-01
    • 2012-12-17
    • 1970-01-01
    相关资源
    最近更新 更多