Pass a template variable to django url using jquery

Viewed 1291

Is it possible to pass a template variable to a django url with jquery? I've tried the standard way of passing the parameter to the django url, but I get a no reverse match.

Javascript

<button id = "testid" href = "{%url 'test:justatest' id=8}">Click here for something</button>

<script type="text/javascript">
  var btn = $('#testid');

      btn.click(function (e) {
        var goto = $(this).attr('href');
          e.preventDefault();

    $.ajax({ 
    url: goto, 
    type: "GET",
    success: function(data){
        console.log(data);
        alert(data);
    }});
});

  </script>

urls.py

path('test/<int:id>',views.TestDetail.as_view(),name="justatest")

I also tried this based off this post but I just get a 404.

<button id = "testid" href = "{%url 'test:justatest'%?id=8}">Click here for something</button>

<script type="text/javascript">
  var btn = $('#testid');

      btn.click(function (e) {
        var goto = $(this).attr('href');
          e.preventDefault();

    $.ajax({ 
    url: goto, 
    type: "GET",
    success: function(data){
        console.log(data);
        alert(data);
    }});
});

  </script>
3 Answers

I do not have experience with passing arguments like that using JS. But Looking at your code I recommend you try adding the % at the end of your statement:

“{% url ‘test:justatest’ id=8 %}”

Tell me how that goes!

WORKING !!

I tried below code and its working.

var url = "{% url 'my-ur-name' 1 %}".replace('1', $(this).attr('temp_id'));

Template rendering occurs in the server before the page is sent out to the browser. And JavaScript executes in the browser after the page has been rendered.

Based on Nids Barthwal's idea, you need something like her answer, but be careful that the replace function is going to be used on the rendered URL.

So in your template, you might have something like:

let goto = "{% url 'justatest' 'temp_arg' %}";

which finaly rendered as:

let goto = "/test/temp_arg/";

now you can replace 'temp_arg' with the jquery variable you want.

let goto = goto.replace('temp_arg', $(this).attr('temp_id'))
Related