簡體   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