Kratos
Kratos

Reputation: 31

Django template tag URL is not working in JavaScript

I want to add an edit button and delete image dynamically to table, but it is showing error Page Not Found at Request URL: http://127.0.0.1:8000/%7B%25%20url%20'expense-edit'%20expense.id%20%25%7D

here is js file

const searchField = document.querySelector("#searchField");
const tableOutput = document.querySelector(".table-output");
const appTable = document.querySelector(".app-table");
const paginationContainer = document.querySelector(".pagination-container");
tableOutput.style.display = 'none';
const noResults = document.querySelector(".no-results");
const tbody = document.querySelector(".table-body");

searchField.addEventListener('keyup', (e) => {
    const searchValue = e.target.value;
    if (searchValue.trim().length > 0) {
        paginationContainer.style.display = "none";
        tbody.innerHTML = "";
        fetch("http://127.0.0.1:8000/search-expenses", {
            body: JSON.stringify({ searchText: searchValue }),
            method: "POST",
        })
            .then((res) => res.json())
            .then((data) => {
                console.log("data", data);
                appTable.style.display = "none";
                tableOutput.style.display = "block";
                console.log("data.length", data.length);
                if (data.length === 0) {
                    noResults.style.display = "block";
                    tableOutput.style.display = "none";

                }
                else {
                    noResults.style.display = "none";
                    data.forEach((item) => {
                        tbody.innerHTML += `
                            <tr>
                                <td>${item.amount}</td>
                                <td>${item.category}</td>
                                <td>${item.description}</td>
                                <td>${item.date}</td>
                                <td><a href="{% url 'expense-edit' expense.id %}" class="btn btn-secondary btn-sm">Edit</a><a href="{% url 'expense-delete' expense.id %}"><img src="{% static 'img/delete.png' %}" width="35" height="35"/></a></td>
                            </tr>`;
                    });
                }
            });
    }
    else {
        noResults.style.display = "none";
        tableOutput.style.display = "none";
        appTable.style.display = "block";
        paginationContainer.style.display = "block";
    }

});

urls.py


from django.urls import path
from . import views
from django.views.decorators.csrf import csrf_exempt

urlpatterns = [
    path('', views.home, name="home"),
    path('expenses', views.index, name='expenses'),
    path('add-expenses', views.add_expenses, name='add-expenses'),
    path('edit-expense/<int:id>', views.expense_edit, name='expense-edit'),
    path('expense-delete/<int:id>', views.delete_expense, name='expense-delete'),
    path('search-expenses', csrf_exempt(views.search_expenses), name='search_expenses'),
    path('expense_category_summary', views.expense_category_summary, name="expense_category_summary"),
    path('stats', views.stats_view, name="stats"),
    path('export_csv', views.export_csv, name="export-csv"),
    path('export_excel', views.export_excel, name="export-excel"),
    path('export_pdf', views.export_pdf, name="export-pdf"),    
]


I want to add a button that has a link to the next page through JavaScript using the Django URL template tag. thanks in advance

Upvotes: 2

Views: 484

Answers (2)

ilyasbbu
ilyasbbu

Reputation: 1749

When you write {% url 'expense-edit' expense.id %}, you're using a Django-specific "language" called Django template language which means that the mentioned syntax can only be "understood" by Django templates.

What you're doing here is loading a separate JavaScript file in which the Django template syntax simply won't work because when browser comes to the point to evaluate that file, {% url 'expense-edit' expense.id %} will look just another string literal, and not what you would expect to.

It should work if you inline your JavaScript example directly into the Django template.

So there is two possible Hacks to do this:

One is putting the written script in your tenplate file as:

<script type="text/javascript">
    const searchField = document.querySelector("#searchField");
    const tableOutput = document.querySelector(".table-output");
    
    ...

</script>

The issue with this approach is the scope of variables as you may not want to declare things globally so it could be considered an easy approach, but not necessarily the best solution.

So the other solution is to change the name of file from script.js to script.js.html and include in your desired template as :

...
{% include "my_app/script.js.html" %}

Upvotes: 2

Manoj Tolagekar
Manoj Tolagekar

Reputation: 1970

Instead of this:

<a href="{% url 'expense-edit' expense.id %}" class="btn btn-secondary btn-sm">Edit</a><a href="{% url 'expense-delete' expense.id %}"><img src="{% static 'img/delete.png' %}" width="35" height="35"/></a></td>

Try this way:

<a href="/edit-expense/{{ expense.id }}" class="btn btn-secondary btn-sm">Edit</a>

<a href="/expense-delete/{{ expense.id }}"><img src="{% static 'img/delete.png' %}" width="35" height="35"/></a></td>

Upvotes: 0

Related Questions