Reversing Django URLs With Extra Options


Question

Suppose I have a URLconf like below, and 'foo' and 'bar' are valid values for page_slug.

urlpatterns = patterns('',
    (r'^page/(?P<page_slug>.*)/', 'myapp.views.someview'),
)

Then, I could reconstruct the URLs using the below, right?

>>> from django.core.urlresolvers import reverse
>>> reverse('myapp.views.someview', kwargs={'page_slug': 'foo'})
'/page/foo/'
>>> reverse('myapp.views.someview', kwargs={'page_slug': 'bar'})
'/page/bar/'

But what if I change my URLconf to this?

urlpatterns = patterns('',
    (r'^foo-direct/', 'myapp.views.someview', {'page_slug': 'foo'}),
    (r'^my-bar-page/', 'myapp.views.someview', {'page_slug': 'bar'}),
)

I expected this result:

>>> from django.core.urlresolvers import reverse
>>> reverse('myapp.views.someview', kwargs={'page_slug': 'foo'})
'/foo-direct/'
>>> reverse('myapp.views.someview', kwargs={'page_slug': 'bar'})
'/my-bar-page/'

However, this throws a NoReverseMatch exception. I suspect I'm trying to do something impossible. Any suggestions on a saner way to accomplish what I want?

Named URLs aren't an option, since I don't want other apps that link to these to need to know about the specifics of the URL structure (encapsulation and all that).

1
13
3/18/2009 8:32:41 PM

You should try naming your urlconfs. Example:

urlpatterns = patterns('',
    url(r'^foo-direct/', 'myapp.views.someview', {'page_slug': 'foo'}, name='foo-direct'),
    url(r'^my-bar-page/', 'myapp.views.someview', {'page_slug': 'bar'}, name='bar-page'),
)

Then just edit your reverses and you should get it working.

>>> from django.core.urlresolvers import reverse
>>> reverse('foo-direct', kwargs={'page_slug': 'foo'})
'/foo-direct/'
>>> reverse('bar-page', kwargs={'page_slug': 'bar'})
'/my-bar-page/'

More info at: Django Docs

20
12/1/2011 10:59:48 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon