3

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>
Reez0
  • 2,512
  • 2
  • 17
  • 39
  • I think the right way to write the url would be "{%url 'justatest' '8'}". But consider passing the id via your view. – dsax7 Nov 04 '18 at 10:10
  • @filtfilt Actually when we use multiple app in the project we need to add app url in main url and while redirecting we need to mention the Appname with the url – Vinay Kumar Jun 21 '19 at 09:51

3 Answers3

0

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!

Felix
  • 84
  • 9
0

WORKING !!

I tried below code and its working.

var url = "{% url 'my-ur-name' 1 %}".replace('1', $(this).attr('temp_id'));
Nids Barthwal
  • 2,205
  • 20
  • 12
0

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'))
mimskydo
  • 46
  • 8