Opened 2 months ago

Closed 2 months ago

#32402 closed Bug (invalid)

django.urls resolve does not resolve typed paths, like <int:pk>

Reported by: HM Owned by: nobody
Component: Core (URLs) Version: 3.1
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


Resolving typed paths like "<int:pk>" doesn't work, see script to reproduce below.

import os

from django.conf import settings
from django.http import HttpResponse
from django.urls import path, reverse, resolve

fname = os.path.splitext(os.path.basename(__file__))[0]
urlpatterns = [
    path('<int:pk>/', lambda r, **kwargs: HttpResponse('Hello, world!'), name='testurl'),

if __name__ == "__main__":
    settings.configure(DEBUG=True, MIDDLEWARE_CLASSES=[], ROOT_URLCONF=fname)

    # Works
    reverse('testurl', kwargs={'pk': 4})

    # Raises Resolver404

This holds for Django 2.2, Django 3.0, Django 3.1 and Django 3.2a1.

I've pdb'ed my way into the django code and the problem seems to be that when URLResolver.resolve() gets around to running RoutePattern.match(path), the path looks like "'<int:pk>/'" but the regex it is checked against, stored on the RoutePattern instance, looks like re.compile('^(?P<pk>[0-9]+)/$'), which obviously will never match.

(I'm using resolve() in a unittest to check that manually created views with externally known paths are properly installed in the urlconf. I get the paths to test from django_extensions's show_urls.)

Change History (2)

comment:1 Changed 2 months ago by HM

Type: UncategorizedBug

comment:2 Changed 2 months ago by Mariusz Felisiak

Component: UncategorizedCore (URLs)
Resolution: invalid
Status: newclosed

resolve() can be used for resolving URL path not for resolving URL patterns, e.g. resolve('/6/') works as expected, see docs.

Please don't use Trac as a support channel. Closing per TicketClosingReasons/UseSupportChannels.

Note: See TracTickets for help on using tickets.
Back to Top