pythondjangodjango-2.0

Django 2.0: NoReverseMatch at /url/ (/pledges/group/7/)


I just have upgraded from Django 1.11 to 2.0. These are the urls I have for one Django application:

urlpatterns = [
    url(r'^logout/$', views.logout, name='logout'),
    url(r'^$', views.home, name='home'),
    url(r'^pledge/(?P<group_id>[0-9]+)/$',
        views.pledge, name='pledge_by_group'),
    # I have more urls, but I have omitted them since they are not relevant
    url(r'^404/$', views.bad_request, name='404')
]

After upgrading, I checked everything was fine. Then, I changed:

url(r'^pledge/(?P<group_id>[0-9]+)/$', views.pledge, name='pledge_by_group')

to:

url('pledge/<int:group_id>/', views.pledge, name='pledge_by_group'),

in order to take advantage of simplified URL routing syntax in Django 2.0. However, I am getting the following error when I try to access http://localhost:8000/pledges/group/7/:

NoReverseMatch at /pledges/group/7/ Reverse for 'pledge_by_group' with keyword arguments '{'group_id': '7'}' not found. 1 pattern(s) tried: ['pledge//']

This is my view:

@login_required(redirect_field_name='')
def group_pledge(request, group_id):
    """Some docstring..."""
    # Some code that is not relevant to the problem

    context = {
        'pledge_url':  reverse('pledges:pledge_by_group',
                        kwargs={'group_id': group_id}),
    } # context has more values, but for practical reasons I don't include them

    return render(request, 'pledges/home.html', context)

According to the error, the problem is in this line:

reverse('pledges:pledge_by_group', kwargs={'group_id': group_id})

Can somebody tell me what is going on and how to fix it?


Solution

  • The new syntax requires the use of path function. For example:

    from django.urls import path
    
    ...
    path('pledge/<group_id>/', views.pledge, name='pledge_by_group'),