Go to Google Groups Home    Django developers
Reverse URL lookup implementation

Adrian Holovaty <holov...@gmail.com>

On the plane from London to Chicago yesterday, I implemented something
that's been discussed on this list lately -- "reverse" URL creation.

I've attached a new urlresolvers.py to this e-mail. It's intended to
replace the one in django/core, and it works with magic-removal only.
(To use it with trunk, just replace the import line at the top to
import Http404 from django.core.exceptions instead of django.http.)
I've also attached unit tests.

Given a view name (e.g. 'myproject.polls.views.poll_detail', as a
string) and any number of positional or keyword arguments, this code
generates the URL according to the first URL pattern in your URLconf
that matches.

The method is reverse() on both the RegexURLPattern and
RegexURLResolver classes.

Here's an example of how it works. Given this root URLconf:

urlpatterns = patterns('',
    (r'^foo/$', 'path.to.foo_view'),
    (r'^dates/(\d{4})/(\w{3})/$', 'path.to.month_view'),
    (r'^people/(?P<state>\w\w)/(?P<name>\w+)/$', 'path.to.person_view'),
)

Here's how to use it:

>>> from django.conf import settings
>>> from django.core import urlresolvers
>>> resolver = urlresolvers.RegexURLResolver(r'^/', settings.ROOT_URLCONF)
>>> resolver.reverse('path.to.foo_view')
'foo/'
>>> resolver.reverse('path.to.month_view', '2005', 'apr')
'dates/2005/apr/'
>>> resolver.reverse('path.to.person_view', state='il', name='adrian')
'people/il/adrian/'
>>> resolver.reverse('path.to.person_view', 'il', 'adrian')

'people/il/adrian/'
# In the following, 'invalidstate' fails the regex test (it isn't two
characters long).
>>> resolver.reverse('path.to.person_view', 'invalidstate', 'adrian')

Traceback (most recent call last):
...
NoReverseMatch

Ideally there'd be a template-tag interface to this. Something like:

    {% link 'path.to.month_view' 2005 'apr' %}
    {% link 'path.to.person_view' state='il' name='adrian' %}

It's implemented by analyzing the regular expression, which was quite
fun. This means it'll probably break for wacky regexes, but I think a
95% solution is fine.

Thoughts?

Adrian

--
Adrian Holovaty
holovaty.com | djangoproject.com

  urlresolvers.py
7K Download

  reverse_unit_tests.py
2K Download