python - Django 2.0 中的反向 URL

标签 python django django-urls django-2.0

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

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

最佳答案

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

使用path()简化语法。

from django.urls import path

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

关于python - Django 2.0 中的反向 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47656775/

相关文章:

python - 如何删除多层括号python中的文本

python - 递归函数无法按预期工作

python - 基于现有数据库表的动态 Django 模型创建

javascript - 如何在 django 中通过 ajax 发布数据?

django - 测试 URL 是否与正确的 View 匹配

python - Django URL 重定向

Python 套接字服务器接收重复数据

python - 如何计算 Django 连接表中的对象数量?

python - 如何定义在django中接受各种字符串的url

python - Anaconda-navigator : byte indices must be integers or slices, 不是 str