Django reverse with JavaScript
Jul 16th, 2010 by diegobz
Taking the cobwebs out of here…
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.>>> get_url_pattern(‘project_deails’)
u’/projects/p/%(project_slug)s/’“”"
return ‘/%s’ % get_resolver(None).reverse_dict.get(urlname)[0][0][0]
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.
Once you have the URL as a string with named args, you can use this JQuery plugin, to resolve the named args using only JavaScript in the client side.
… and that’s it!