Calling Django `reverse` in client-side Javascript

noio picture noio · Apr 27, 2010 · Viewed 19.2k times · Source

I'm using Django on Appengine. I'm using the django reverse() function everywhere, keeping everything as DRY as possible.

However, I'm having trouble applying this to my client-side javascript. There is a JS class that loads some data depending on a passed-in ID. Is there a standard way to not-hardcode the URL that this data should come from?

var rq = new Request.HTML({
    'update':this.element,
}).get('/template/'+template_id+'/preview'); //The part that bothers me.

Answer

Anatoly Rr picture Anatoly Rr · Jun 29, 2012

There is another method, which doesn't require exposing the entire url structure or ajax requests for resolving each url. While it's not really beautiful, it beats the others with simplicity:

var url = '{% url blog_view_post 999 %}'.replace (999, post_id);

(blog_view_post urls must not contain the magic 999 number themselves of course.)