Transfer the URL of a template with a PK parameter from JavaScript to Django

I successfully implemented Ajax Search and the results are loaded into a table within a template file. The table header rows are static, and I iterate through each result to append them in < tr > < td >... using a foreach loop.

       if (data.length === 0) {
                tableOutput.innerHTML = '<h3>No results found.</h3>';

            } else {
                nbResults.style.display = "block"
                nbResults.innerHTML = data.length + " products found"
                data.forEach((item) => {
                    my_url = "{% url 'auto-product-details' ${item.id} %}"

                    if (item.etat__etat == "Echange Standard") {
                        var etat = "ES";
                    } else {
                        var etat = item.etat__etat;
                    }
                    if (item.cau == "0.00") {
                        var cau = "nc";
                    } else {
                        var cau = item.cau;
                    }


                    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" class="btn btn-sm btn-labeled btn- 
                             info">
                        <span style="color: #fff;" class="btn-label"><i class="fas 
                        fa-sign-in-alt"></i></span></a></td>
                    </tr>
                    `;

The issue arises when trying to include Django template syntax for the URL using:

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

This transformation occurs resulting in:

/facture/%7B%%20url%20'auto-product-details'%2036%20%%7D

Attempts were made to construct the URL piece by piece in JS and replace {item.id } after creating a base URL without PK, but no success was achieved. It appears that special characters are being converted to HTML. Is there a way to accomplish this task as intended?

Answer №1

One strategy is to introduce an additional variable:

new_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="'+ new_url +'"> 
        <button type="button" class="btn btn-sm btn-labeled btn- 
             info">
        <span style="color: #fff;" class="btn-label"><i class="fas 
        fa-sign-in-alt"></i></span></a></td>
    </tr>
    ';

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to display this JSON data using mustache.js without needing to iterate through a

Here is the JSON data: var details = [ { "event": { "name": "txt1", "date": "2011-01-02", "location": "Guangzhou Tianhe Mall" } ...

How can I locate and substitute a specific script line in the header using Jquery?

I need to update an outdated version of JQuery that I have no control over, as it's managed externally through a CMS and I can't make changes to it. But I want to switch to a newer version of JQuery. Here is the old code: <script type="text/ ...

Steps for extracting a value from a webpage

Hello there, I'm in need of some assistance with a project I'm working on. I've taken it upon myself to delve into the world of nodeJS and restAPI by creating a simple app to track the prices of BTC, LTC, ETH, and BCH using Postman for API ...

Developing additional fields within a serializer that retrieve attributes from a different model

After making an API call to api/business-review/3abe3a1e-199c-4a4b-9d3b-e7cb522d6bed/, the current response is as follows: [ { "id": "3abe3a1e-199c-4a4b-9d3b-e7cb522d6bed", "date_time": "2016-05-31T19:18:24Z", "review": "Anothe ...

How should you proceed when npm install cannot locate a specific dependency, even though you can easily download it manually?

Currently, I am faced with a dilemma while attempting to execute a JavaScript file that is accompanied by a package.json file. The issue arises during the npm install command in the folder as it fails to locate one of the dependencies. To address this pro ...

Tips for integrating AudioControl with Phonegap

I couldn't find a suitable plugin, so I decided to create my own. My goal is to activate silent mode using a JavaScript command, however, I am encountering an error with the undefined method getSystemService. It seems like there may be a problem with ...

Continuously encountering issues with the callback function in passport.js

I am currently working on setting up a slack login using passport.js, Sequelize, and Node. However, I keep encountering an error upon returning. Here are my code snippets: app.get('/auth/slack', passport.authorize('slack')); ...

Why is Django/DRF throwing a Model error when using a serializer that is not associated with a model?

Looking for assistance with my API endpoint that requires two post parameters: user_id and code Here is the relevant serializer: class ConfirmationCodeSerializer(serializers.Serializer): user_id = serializers.CharField(max_length=36) code = seria ...

Bootstrap revamps dropdown menu code into a convoluted mess

I recently started working on a project with the Material Design theme from for a CodeIgniter application. However, I've encountered an issue with the dropdown functionality. It seems that Bootstrap is altering the original code, transforming it from ...

Is there a method to place two items in a flex container while only centering one of them?

I managed to achieve the desired effect using absolute positioning, but I know this is not the most elegant solution and it lacks re-usability. Is there a way for me to group these two elements in a flex container and center only the text? Also, I'm f ...

Adjust the field of view of the camera in ThreeJS

I'm currently working on adjusting the field of vision for a camera without having to create a new one. So far, I've successfully achieved this for the position using the following code: camera.position.set() Now, I'd like to implement a s ...

Trackball's controls are not responding correctly

Recently, I have been using trackball controls and I've come across a strange bug. When I pan and then zoom out from my new position, the controls start to behave erratically, pulling towards the origin (the further I pan, the worse the issue becomes) ...

Convert XML data into a structured table format

We have an XML file named "servers.xml" that needs to be parsed. This file is located on the same server where we want it to be parsed, in the same folder. <root> <list> <server> <server name="28 Disconnects La ...

Transferring PHP Multidimentional Array data to Javascript

I've scoured this website for a solution, but unfortunately, nothing seems to be working. So, I've decided to reach out to you all for help. I hope you can assist me with my issue. The problem lies within a PHP file that is populating an array w ...

Showing images from a URL in Django using sorl-thumbnail

I have implemented solr-thumbnail successfully in various parts of my project. However, this time I am attempting to display an image from a URL. Here is my code snippet: {% load thumbnail %} {% thumbnail profile_picture_url "150x150" crop="center ...

Experimenting with Jquery Ajax JSON on a local environment

Seeking help in testing if the form data is being saved as JSON format after submitting it via API. Any assistance would be greatly appreciated. <form id="reg-form" method="post" action=""> <div class="form-group"> <label for="yourname" ...

What is the best way to sort through data retrieved by a server component in a NextJS 13 AppDir?

I've hit a roadblock trying to integrate a search bar that filters server-fetched data in my project using NextJS 13 and AppDir. Despite numerous attempts, I can't seem to get it right. It feels like there's something crucial I'm overlo ...

Graph is not showing up when navigating through page

On my List page (List.Html), users can select multiple rows to display the data in a chart using C3. However, when clicking on the compareList() button to navigate to the Chart page (Chart.Html), the chart does not display properly. It seems that the chart ...

Python-Django module not found

Having trouble starting Django with the command cd manage.py runserver, as there is an issue with a module named 'first'. Screenshots of my file can be found here: (https://i.sstatic.net/wcRod.png) (https://i.sstatic.net/8o7sB.png) Viewing views ...

Vue-bootstrap spinbutton form with customizable parameters

I am in need of a custom formatter function for the b-form-spinbutton component that depends on my data. I want to pass an extra argument to the :formatter-fn property in the code snippet below, but it is not working as expected. <b-form-spinbutton :for ...