Django : How can I see a list of urlpatterns?

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?


Solution 1:

If you want a list of all the urls in your project, first you need to install django-extensions, add it to your settings like this:

INSTALLED_APPS = (
...
'django_extensions',
...
)

And then, run this command in your terminal

./manage.py show_urls

For more information you can check the documentation.

Solution 2:

Try this:

from django.urls import get_resolver
get_resolver().reverse_dict.keys()

Or if you're still on Django 1.*:

from django.core.urlresolvers import get_resolver
get_resolver(None).reverse_dict.keys()

Solution 3:

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