Reversing Django URLs With Extra Options

Posted by Justin Voss on Stack Overflow See other posts from Stack Overflow or by Justin Voss
Published on 2009-03-18T19:45:58Z Indexed on 2010/05/18 1:00 UTC
Read the original article Hit count: 511

Filed under:
|

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).

© Stack Overflow or respective owner

Related posts about python

Related posts about django