Ibrahim Fakih
Ibrahim Fakih

Reputation: 61

Passing variable through Django template url tag

I am trying to pass a variable through the Django template url tag with little success.

My path in the urls.py:

path("viewListing/<int:listingID>", views.bookListing, name="viewListing")

In the template, I am using javascript to generate the listingID with a for loop.

for(j=0; j<5; j++){
  var thisID = (data[j].id)
  imgA.href = "{% url 'viewListing' thisID %}";
}

However, I am getting this error

Reverse for 'viewListing' with arguments '('',)' not found. 1 pattern(s) tried: ['viewListing/(?P<listingID>[0-9]+)$']

If I pass a number instead of thisID, for instance 1, the code works fine.

So my question is, how can I make this work with a variable.

Upvotes: 1

Views: 606

Answers (1)

farooq
farooq

Reputation: 489

You cannot use django tags inside Javascript. They are server side. What you can do instead is cache the url in a variable and then concatenate the ID to it like this:

for(j=0; j<5; j++){
    var thisID = (data[j].id)
    var listing_url = "{% url 'viewListing' listingID=9999 %}";
    imgA.href = listing_url.replace(/9999/, thisID);
}

Credit goes to @MikeLee: Get javascript variable's value in Django url template tag

Upvotes: 1

Related Questions