Home > OS >  Pass from Javascript to Django a template URL with PK
Pass from Javascript to Django a template URL with PK

Time:02-17

I implemented Ajax Search with success and results are loaded in a table which is in a template file. My TH are static and I append each result in < tr > < td >... in a foreach loop.

tableBody.innerHTML  = `
                    <tr>
                        <td>${item.sku}</th>
                        <td>${item.etat}</td>
                        <td ${item.nom}</td>
                        <td>${item.sst1}</td>
                        <td>${item.sst2}</td>
                        <td>${item.sst3}</td>
                        <td>${item.pua}</td>
                        <td>${item.cau}</td>
                        <td><a href="/facture/auto-product-details/${item.id}"> 
                        <button type="button" >
                        <span style="color: #fff;" ><i ></i></span></a></td>
                    </tr>
                    `;

My problem is I had (above) to "hardcode" my URL "auto-product-details" because when I try to respect Django template syntax like this :

<td><a href="{% url 'auto-product-details' ${item.id} %}">...

but the URL is transformed in

/facture/{% url 'auto-product-details' 36 %}

I tried to build piece by piece my URL in JS, tried to replace the {item.id } after the creation of a base (var) url without PK ... no success. It seems the special characters are transformed in HTML.

Is there a way to achieve what I want to do ?

CodePudding user response:

You could use an intermediate variable:

my_url = "{% url 'auto-product-details' ${item.id} %}"
tableBody.innerHTML  = '
    <tr>
        <td>${item.sku}</th>
        <td>${item.etat}</td>
        <td ${item.nom}</td>
        <td>${item.sst1}</td>
        <td>${item.sst2}</td>
        <td>${item.sst3}</td>
        <td>${item.pua}</td>
        <td>${item.cau}</td>
        <td><a href="' my_url '"> 
        <button type="button" >
        <span style="color: #fff;" ><i ></i></span></a></td>
    </tr>
    ';

CodePudding user response:

This will never work the way that you think because what Django does is take tags like {{ item.id }} or {% url 'auto-product-details' item.id %} and replaces that with the values when you render the template. Your JavaScript will load AFTER that happens. In fact, /facture/{% url 'auto-product-details' 36 %} is just the url-encoded string (i.e., the } is just the character, }.

I'm not sure of what you're trying to achieve, but you can just do all this in your template without any JavaScript assuming you pass items with all the items you will iterate through in your render function. Then in your template, something like this.

{% for item in items %}
    <tr>
        <td>{{ item.sku }}</th>
        ...
        <td><a href="{% url 'auto-product-details' item.id %}">
        <button type="button" >
        <span style="color: #fff;" ><i ></i></span></a></td>
    </tr>
{% endfor %}
  • Related