Reputation: 31
I have a model, Item, with several attributes such as name, type, and owner. In my template the list of Items is iterated through and displayed in a table. What I would like to do is reorder the items in the table when a button next to the table head is clicked i.e. when the button next to Name is clicked the elements in the table are sorted by alphabetical order. Here is my template:
{% extends 'inventory/base.html' %}
{% block content %}
<a class="btn btn-default" href="{% url 'inventory:entry' %}">New Item</a>
<script>
jQuery(document).ready(function($) {
$(".clickable-row").click(function() {
window.location = $(this).data("href");
});
});
</script>
{% if item_list %}
<table>
<tr>
<th>Name <button class="btn btn-default" href="order_table"></button></th>
<th>Type <button class="btn btn-default" href="order_table"></button></th>
<th>Barcode/Model No. <button class="btn btn-default" href="order_table"></button></th>
<th>Owner <button class="btn btn-default" href="order_table"></button></th>
<th>Edit <button class="btn btn-default" href="order_table"></button></th>
</tr>
{% for item in item_list %}
<tr class="clickable-row itemrow" data-href="{% url 'inventory:details' item.id %}">
<td>{{ item.name }}</td>
<td>{{ item.itemType }}</td>
<td>{{ item.barcode }}</td>
<td>{{ item.owner.username }}</td>
<td><a href="{% url 'inventory:edit' item.id %}" class="btn btn-default">Edit</a></td>
</tr>
{% endfor %}
</table>
{% endif %}
{% endblock %}
Upvotes: 0
Views: 2199
Reputation: 20102
instead of a button use a link and pass a parameter to the view:
<th><a href="{{ url('myurl') }}?sort=name">Name </a></th>
in the django view you can retrieve the sort parameter using : request.GET.get('sort', 'your_default_sort')
and use it to order the queryset. If you're using FBV change it manually in the function, and if you're using CBV just override the get_ordering()
method of your class
however, It would me much much easier with a client-side solution like datatables
Hope this helps
Upvotes: 1