[Fixed]-Reversing Django URLs With Extra Options

21👍

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

7👍

Here’s what we do.

urls.py has patterns like this

url(r'^(?P< datarealm >.*?)/json/someClass/(?P<object_id>.*?)/$', 'json_someClass_resource', ),

views.py as reverse calls like this

    object = SomeModel.objects.get(...)
    url= reverse('json_someClass_resource', kwargs={'object_id':object.id,'datarealm':object.datarealm.name})
👤S.Lott

4👍

Named urls ought to be an option. Your case is highlighted in the Django reference:

http://docs.djangoproject.com/en/dev/topics/http/urls/?from=olddocs#id2

I’m not sure the designers left another work-around; they expected named urls to cover it.

May I digress about encapsulation? Thanks. There are two main reasons:

  1. Abstraction–no one wants to see the details
  2. Security–no one should see the details

As for 1, you can get a decent amount of mileage out of it in python, and Django is an excellent example. As for 2, it’s an interpreted language. Either you’re running it where it’s written, or you’re shipping off compiled .pyc files. If that’s really what you’re doing, then compile the url conf.

Finally, it seems less encapsulated to let other apps know about the functions than the url structure. But if you really disagree, I think you’ll have to implement a more flexible reverse method yourself.

Leave a comment