Django : How can I see a list of urlpatterns?

Viewed 115294

How can I see the current urlpatterns that "reverse" is looking in?

I'm calling reverse in a view with an argument that I think should work, but doesn't. Any way I can check what's there and why my pattern isn't?

20 Answers

Django >= 2.0 solution

I tested the other answers in this post and they were either not working with Django 2.X, incomplete or too complex. Therefore, here is my take on this:

from django.conf import settings
from django.urls import URLPattern, URLResolver

urlconf = __import__(settings.ROOT_URLCONF, {}, {}, [''])

def list_urls(lis, acc=None):
    if acc is None:
        acc = []
    if not lis:
        return
    l = lis[0]
    if isinstance(l, URLPattern):
        yield acc + [str(l.pattern)]
    elif isinstance(l, URLResolver):
        yield from list_urls(l.url_patterns, acc + [str(l.pattern)])
    yield from list_urls(lis[1:], acc)

for p in list_urls(urlconf.urlpatterns):
    print(''.join(p))

This code prints all URLs, unlike some other solutions it will print the full path and not only the last node. e.g.:

admin/
admin/login/
admin/logout/
admin/password_change/
admin/password_change/done/
admin/jsi18n/
admin/r/<int:content_type_id>/<path:object_id>/
admin/auth/group/
admin/auth/group/add/
admin/auth/group/autocomplete/
admin/auth/group/<path:object_id>/history/
admin/auth/group/<path:object_id>/delete/
admin/auth/group/<path:object_id>/change/
admin/auth/group/<path:object_id>/
admin/auth/user/<id>/password/
admin/auth/user/
... etc, etc

In Django 3.0, it's as easy as:

from django.urls import get_resolver
print(get_resolver().url_patterns)

Prints: [<URLPattern '' [name='home']>, <URLPattern '/testing' [name='another_url']>]

Here is a quick and dirty hack to just get the information you need without needing to modify any of your settings.

$ pip install django-extensions
$ python manage.py shell -c 'from django.core.management import call_command; from django_extensions.management.commands.show_urls import Command; call_command(Command())'

This is piggy backing off @robert 's answer. While correct, I didn't want to have django-extensions as a dependency even if it was for just a second.

Minimalist solution for django 2.0

For instance, if you're looking for an url that's on the first app of installed_apps, you can access it like that:

from django.urls import get_resolver
from pprint import pprint

pprint(
    get_resolver().url_patterns[0].url_patterns
)

Django 1.8, Python 2.7+ Just run these commands in your Shell. Python manage.py shell and execute the following code.

from django.conf.urls import RegexURLPattern, RegexURLResolver
from django.core import urlresolvers
urls = urlresolvers.get_resolver(None)

def if_none(value):
    if value:
        return value
    return ''

def print_urls(urls, parent_pattern=None):
    for url in urls.url_patterns:
        if isinstance(url, RegexURLResolver):
            print_urls(url, if_none(parent_pattern) + url.regex.pattern)
        elif isinstance(url, RegexURLPattern):
            print(if_none(parent_pattern) + url.regex.pattern)

print_urls(urls)

Django >= 2.0 List Solution

adopted from @CesarCanassa

from django.conf import settings
from django.urls import URLPattern, URLResolver

URLCONF = __import__(settings.ROOT_URLCONF, {}, {}, [''])

def list_urls(patterns, path=None):
    """ recursive """
    if not path:
        path = []
    result = []
    for pattern in patterns:
        if isinstance(pattern, URLPattern):
            result.append(''.join(path) + str(pattern.pattern))
        elif isinstance(pattern, URLResolver):
            result += list_urls(pattern.url_patterns, path + [str(pattern.pattern)])
    return result

You can create a dynamic import to gather all URL Patterns from each application in your project with a simple method like so:

def get_url_patterns():
    import importlib
    from django.apps import apps

    list_of_all_url_patterns = list()
    for name, app in apps.app_configs.items():
        # you have a directory structure where you should be able to build the correct path
        # my example shows that apps.[app_name].urls is where to look
        mod_to_import = f'apps.{name}.urls'
        try:
            urls = getattr(importlib.import_module(mod_to_import), "urlpatterns")
            list_of_all_url_patterns.extend(urls)
        except ImportError as ex:
            # is an app without urls
            pass

    return list_of_all_url_patterns

list_of_all_url_patterns = get_url_patterns()

I recently used something like this to create a template tag to show active navigation links.

from django.urls.resolvers import RegexPattern,RoutePattern
from your_main_app import urls

def get_urls():
    url_list = []
    for url in urls.urlpatterns:
        url_list.append(url.pattern._regex) if isinstance(url.pattern, RegexPattern) else url_list.append(url.pattern._route)

    return url_list

Here your_main_app is the app name where your settings.py file is placed

Yet another adaption of @Cesar Canassa 's generator magic. This can be added to the yourapp/management/commands/dumpurls.py director of your app so that it'll be accessible as a subcommand in management.py.

note: I added a line to make sure it filters for only yourapp. Update or remove it accordingly if additional URLs are desired.

As a management.py Subcommand

Deploy Path: yourapp/management/commands/dumpurls.py

from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from django.urls import URLPattern, URLResolver

def list_urls(lis, acc=None):

    if acc is None:
        acc = []
    if not lis:
        return
    l = lis[0]
    if isinstance(l, URLPattern):
        yield acc + [str(l.pattern),l.name]
    elif isinstance(l, URLResolver):
        yield from list_urls(l.url_patterns, acc + [str(l.pattern)])
    yield from list_urls(lis[1:], acc)

class Command(BaseCommand):
    help = 'List all URLs from the urlconf'

    def handle(self, *args, **options):

        urlconf = __import__(settings.ROOT_URLCONF, {}, {}, [''])

        records, glen, nlen = [], 0, 0

        for p in list_urls(urlconf.urlpatterns):
            record = [''.join(p[:2]), p[2]]

            # Update me, or add an argument
            if record[0].startswith('yourapp'):

                clen = len(record[0])
                if clen > glen: glen = clen

                clen = len(record[1])
                if clen > nlen: nlen = clen
                
                records.append(record)


        self.stdout.write('{:-<{width}}'.format('',width=glen+nlen))
        self.stdout.write('{:<{glen}}Name'.format('Path',glen=glen+4))
        self.stdout.write('{:-<{width}}'.format('',width=glen+nlen))
        for record in records:
            self.stdout.write('{path:<{glen}}{name}'.format(path=record[0],
                name=record[1],
                glen=glen+4))
        self.stdout.write('{:-<{width}}'.format('',width=glen+nlen))

Sample Output

(env) django@dev:myproj~> ./manage.py dumpurls
-------------------------------------------------------------------------------------------------------
Path                                                                        Name
-------------------------------------------------------------------------------------------------------
yourapp/^api-key/$                                                          api-key-list
yourapp/^api-key\.(?P<format>[a-z0-9]+)/?$                                  api-key-list
yourapp/^attacks/$                                                          attack-list
yourapp/^attacks\.(?P<format>[a-z0-9]+)/?$                                  attack-list
yourapp/^attack-histories/$                                                 attackhistory-list
yourapp/^attack-histories\.(?P<format>[a-z0-9]+)/?$                         attackhistory-list
yourapp/^files/$                                                            file-list
yourapp/^files\.(?P<format>[a-z0-9]+)/?$                                    file-list
yourapp/^modules/$                                                          module-list
yourapp/^modules\.(?P<format>[a-z0-9]+)/?$                                  module-list
import subprocces

res = subprocess.run(
    'python manage.py show_urls',
    capture_output=True,
    shell=True,
)
url_list = [
    line.split('\t')[0]
    for line in res.stdout.decode().split('\n')
]

In case you are using DRF, you can print all the URL patterns for a particular router by printing the urlpatterns from router.get_urls() (within your Django app's urls.py file).

Open your apps urls.py and add the print statement to the bottom of the file, so the whole file might look like this:

import pprint

from django.urls import include, path
from rest_framework import routers

from . import views

router = routers.DefaultRouter()
router.register(r"users", views.UserViewSet, basename="User")
router.register(r"auth", views.AuthenticationView, basename="Auth")
router.register(r"dummy", views.DummyViewSet, basename="Dummy")
router.register("surveys", views.SurveyViewSet, basename="survey")

urlpatterns = [
    path("", include(router.urls)),
]

pprint.pprint(router.get_urls())

The patterns are then printed like this:

[<URLPattern '^users/$' [name='User-list']>,
 <URLPattern '^users\.(?P<format>[a-z0-9]+)/?$' [name='User-list']>,
 <URLPattern '^users/admins/$' [name='User-admins']>,
 <URLPattern '^users/admins\.(?P<format>[a-z0-9]+)/?$' [name='User-admins']>,
 <URLPattern '^users/current/$' [name='User-current']>,
 <URLPattern '^users/current\.(?P<format>[a-z0-9]+)/?$' [name='User-current']>,
 <URLPattern '^users/(?P<pk>[^/.]+)/$' [name='User-detail']>,
 <URLPattern '^users/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$' [name='User-detail']>,
 <URLPattern '^auth/login/$' [name='Auth-login']>,
...
]
Related