Добавление ссылок в строки таблицы данных в javascript или jquery
Я использую django. Вот мой код:
<div class="card-body">
<div class="table-responsive">
<table id="datatables" class="table table-striped table-bordered text-nowrap w-100">
<thead>
<tr>
<th class="wd-15p">devEUI</th>
<th class="wd-15p">appID</th>
<th class="wd-20p">Type machine</th>
<th class="wd-20p">Date création</th>
</tr>
</thead>
<tbody>
{% for machine in machines %}
<tr>
<a href="{% url 'details_of_element' %}">
<td>{{machine.devEUI}}</td>
<td>{{machine.appID}}</td>
<td>{{machine.type_machine}}</td>
<td>{{machine.date_creation}}</td>
</a>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
Не работает. Я хочу добавить ссылку к каждой строке, чтобы увидеть подробности каждого элемента. Как я могу сделать это с помощью django, jquery или javascript?
Для detail_view потребуется некоторая идентификация, чтобы получить конкретный экземпляр модели в Django. Обычно это уникальный первичный ключ, такой как id. Чтобы указать эту идентификацию, нам нужно определить ее в urls.py
вашего приложения.
urls.py
from django.urls import path
# importing views from views..py
from .views import detail_view
urlpatterns = [
path('<id>', detail_view, name='details_of_element' ),
]
views.py
from django.shortcuts import render
# relative import of Model
from .models import Machine
# pass id attribute from urls
def detail_view(request, id):
machine = Machine.objects.get(id = id)
return render(request, "detail_view.html", {'machine': machine})
machine_list.html
<tbody>
{% for machine in machines %}
<tr>
<a href="{% url 'details_of_element' machine.id %}">
<td>{{machine.devEUI}}</td>
<td>{{machine.appID}}</td>
<td>{{machine.type_machine}}</td>
<td>{{machine.date_creation}}</td>
</a>
</tr>
{% endfor %}
</tbody>
Я решил проблему с помощью следующего кода
<div class="card-body">
<div class="table-responsive">
<table id="datatables" class="table table-striped table-bordered text-nowrap w-100">
<thead>
<tr>
<th class="wd-15p">devEUI</th>
<th class="wd-15p">appID</th>
<th class="wd-20p">Type machine</th>
<th class="wd-20p">Date création</th>
</tr>
</thead>
<tbody>
{% for machine in machines %}
<tr data-href="{% url 'details_url' %}">
<td>{{machine.devEUI}}</td>
<td>{{machine.appID}}</td>
<td>{{machine.type_machine}}</td>
<td>{{machine.date_creation}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
js
<script>
document.addEventListener("DOMContentLoaded",() =>{
const rows = document.querySelectorAll("tr[data-href]");
rows.forEach(row => {
row.addEventListener("click", () => {
window.location.href = row.dataset.href;
});
});
});
</script>