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
Simply type in a url you know does not exist and the server will return an error message with a list of url patterns.
For example, if you're running a site at http://localhost:8000/something
Type in
http://localhost:8000/something/blahNonsense, and your server will return the url search list and display it in the browser
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
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
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