tags:

views:

331

answers:

3

Is there a way to get the complete django url configuration?

For example Django's debugging 404 page does not show included url configs, so this is not the complete configuration.


Answer: Thanks to Alasdair, here is an example script:

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.urlpatterns)
A: 

If you are running Django in debug mode (have DEBUG = True in your settings) and then type a non-existent URL you will get an error page listing the complete URL configuration.

Van Gale
As I mentioned, this error page does not show the complete configuration because it does not include information about *included* url configurations.
Michael
I understood exactly what you meant about INCLUDED url configurations, but answered from faulty memory because I didn't have immediate access to a test site. I swear I've see the URL error page put a space between the top level url and the included urls but see now it doesn't. So the answer is NO, there is no way to see the complete configuration.
Van Gale
The error page shows only _relevant_ included url configurations. E.G. the 404 page for `/news/bad_url/` will display included urls from the `news` app, but not from the `sport` app.
Alasdair
A: 

Are you looking for the urls evaluated or not evaluated as shown in the DEBUG mode? For evaluated, django.contrib.sitemaps can help you there, otherwise it might involve some reverse engineering with Django's code.

Thierry Lam
+3  A: 

Django is Python, so introspection is your friend.

In the shell, import urls. By looping through urls.urlpatterns, and drilling down through as many layers of included url configurations as possible, you can build the complete url configuration.

>import urls
>urls.urlpatterns

The list urls.urlpatterns contains RegexURLPattern and RegexURLResolver objects.

For a RegexURLPattern object p you can display the regular expression with

>p.regex.pattern

For a RegexURLResolver object q, which represents an included url configuration, you can display the first part of the regular expression with

>q.regex.pattern

and then use

>q.urlpatterns

which will return a further list of RegexURLResolver and RegexURLPattern objects.

Alasdair
Good idea! I made a simple script here: http://code.activestate.com/recipes/576974/
Michael
That's an elegant function. I started trying to write one, but it involved checking object types to see if they were `RegexURLPattern` or `RegexURLResolver`. Using `has_attr` is a much better idea. You should put your function in answer here on Stack Overflow. I'd upvote it.
Alasdair