Search code examples
pythondjangourlurl-pattern

In Django, how to find out what URL pattern matched for a request?


I'm working on an old Django project with a lot of URL patterns. Sometimes, it's not clear for me which view was run by the dispatcher. Is there any way to see what URL pattern matched for a particular request in Django?


Solution

  • You can use the resolve(…) function [Django-doc] for that.

    If we define as urlpatterns:

    from django.urls import path
    from app.views import some_view
    
    urlpatterns = [
        path('some/<slug:name>', some_view, name='some_view')
    ]

    It will return us:

    >>> resolve('/some/view/')
    ResolverMatch(func=app.views.some_view, args=(), kwargs={'name': 'view'}, url_name=some_view, app_names=[], namespaces=[], route=some/<slug:name>/)
    

    It thus returns us a ResolverMatch object [Django-doc]. We can query this object like:

    >>> result = resolve('/some/view/')
    >>> result.func
    <function some_view at 0x7fc09facf0d0>
    >>> result.args
    ()
    >>> result.kwargs
    {'name': 'view'}
    >>> result.url_name
    'some_view'
    >>> result.app_names
    []
    >>> result.namespaces
    []
    >>> result.route
    'some/<slug:name>/'
    

    Here func thus holds a reference to the function that will be triggered, args and kwargs hold the positional and named parameters in the path respectively, url_name the name of the view, etc.

    If the path is unclear, you could use reverse [Django-doc] function instead.

    urlpatterns = [
        path('some/view', some_view_func, name='some_new_view'),
        path('some/<int:pk>', some_view_with_id, name='some_with_id'),
    ]
    

    Without arguments

    Note: This only works for url configurations without arguments.

    In [1]: reverse('some_new_view')
    Out[1]: 'some/view'
    

    To match url view names with arguments

    In [1]: reverse('some_with_id', kwargs={'pk': 1})
    Out[1]: 'some/1'