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 wa
There is a recipe on activestate
import urls
def show_urls(urllist, depth=0):
for entry in urllist:
print(" " * depth, entry.regex.pattern)
if hasattr(entry, 'url_patterns'):
show_urls(entry.url_patterns, depth + 1)
show_urls(urls.url_patterns)
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():
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.
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()
def get_resolved_urls(url_patterns):
url_patterns_resolved = []
for entry in url_patterns:
if hasattr(entry, 'url_patterns'):
url_patterns_resolved += get_resolved_urls(
entry.url_patterns)
else:
url_patterns_resolved.append(entry)
return url_patterns_resolved
In python manage.py shell
import urls
get_resolved_urls(urls.urlpatterns)
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']>]
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
)