user7795844
user7795844

Reputation:

Reverse URL in Django 2.0

The new Django 2.0 update broke my way of reversing url and printing it to the template. 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.

Upvotes: 2

Views: 3926

Answers (1)

Alasdair
Alasdair

Reputation: 308869

In Django 2.0, url() is an alias for re_path() and still uses regular expressions.

Use path() for the simplified syntax.

from django.urls import path

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

Upvotes: 3

Related Questions