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.
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)
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.
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.
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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With