When django-tables2 renders an unsorted table, and I want to sort by one column, I click it, the default behaviour is to sort it in ascending order.
Is there any way I can change it so that the first click sorts in descending order?
It can be done, here is how.
First you have to override the default table.html template that is used for rendering table (if you are not already using your own template). You can start with the one included in django-tables2.
Secondly, in the template, find the anchor used for sorting:
{% if column.orderable %}
<th {{ column.attrs.th.as_html }}><a href="{% querystring table.prefixed_order_by_field=column.order_by_alias.next %}">{{ column.header }}</a></th>
{% else %}
And change this to:
{% if column.orderable %}
{% with "-"|add:column.name as sort_col_name %}
<th {{ column.attrs.th.as_html }}><a href="{% querystring table.prefixed_order_by_field=column.order_by_alias.opposite|default:sort_col_name %}">{{ column.header }}</a></th>
{% endwith %}
{% else %}
So we are basically just adding a -
in front of the column name by default in order to force descending sort in case when the page is loaded without sorting, and turning to .opposite
instead of .next
. We need to do this because .next
will always be defined whereas .opposite
will be None on the page load without sort, and the default filter will get executed. When sorting is defined, .opposite
will properly toggle the sort order.
Note that this is not tested, and if you have problems take a look into the django-tables2 source for more info.