Here I go to cite a way that can ‘solve’ the URL reversing problem when you are using a Django app that uses some JavaScript and Ajax requests.

Django has a very nice way to resolve URLs based on its name and optionally some args. It uses the regex pattern defined in the related urls.py file of the given app. Example:

from django.core.urlresolvers import reverse

reverse(‘project_detail’, args=['foo'])
‘/projects/p/foo/’

reverse(‘project_detail’, args=['bar'])
‘/projects/p/bar/’

The problem turns when you want to make a Ajax request based on some dynamic data from a form or something. As some URLs sometimes need arguments to be resolved, we can’t always pre-reverse and attach them to the Context, on the Django response.

For the record, I found an alternative here. With it you can take the args from the browser and request through Ajax to Django the resolved URL. It’s pretty cool, but I think it was a bit expensive to multiply by 2 the number of requests to the server.

It made me think on another approach, where I would pre-fill in the Context response of Django, the URL already resolved, but with named args like, %(project)s, for the required arguments. I ended up with this:

from django.core.urlresolvers import get_resolver

def get_url_pattern(urlname):
“”"
Return pattern for an URL based on its name.