Taking the cobwebs out of here…
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
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
Return pattern for an URL based on its name.
return ‘/%s’ % get_resolver(None).reverse_dict.get(urlname)
As you can notice, passing an URL name to that function will give you the resolved URL with named args. I’m not really aware about corner cases, so feel free to give any comment on it.
… and that’s it!