Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Django `reverse` in client-side Javascript

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. 
like image 360
noio Avatar asked Apr 27 '10 19:04

noio


People also ask

How do I reverse in Django?

reverse() If you need to use something similar to the url template tag in your code, Django provides the following function: reverse (viewname, urlconf=None, args=None, kwargs=None, current_app=None)

What is redirect reverse in Django?

It is called reverse because it is a reverse process of determining which view should be called for a given URL (which process is called resolving). Redirects are not specific to Django or any other web frameworks. Redirect means that for a given URL (or action), the user should be instructed to visit a specific URL.

What is reversing of url in Django?

the reverse function allows to retrieve url details from url's.py file through the name value provided there. This is the major use of reverse function in Django. Syntax: Web development, programming languages, Software testing & others. from django.urls import reverse.


2 Answers

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.)

like image 53
Anatoly Rr Avatar answered Sep 23 '22 14:09

Anatoly Rr


Having just struggled with this, I came up with a slightly different solution.

In my case, I wanted an external JS script to invoke an AJAX call on a button click (after doing some other processing).

In the HTML, I used an HTML-5 custom attribute thus

<button ... id="test-button" data-ajax-target="{% url 'named-url' %}"> 

Then, in the javascript, simply did

$.post($("#test-button").attr("data-ajax-target"), ... ); 

Which meant Django's template system did all the reverse() logic for me.

like image 32
kdopen Avatar answered Sep 25 '22 14:09

kdopen