I display a database table using django-tables2. All appears OK, but clicking on the column headers does not sort by that column. The headers are clickable, but in their html has no url text in it, e.g.:
<div class="table-container">
<table class="paleblue"><thead><tr><th class="id orderable sortable"><a href="">ID</a>
</th><th class="orderable sortable system"><a href="">System</a></th> ...
I checked the django-tables2 template source and it sais this:
... <a href="{% querystring table.prefixed_order_by_field=column.order_by_alias.next %}"> ...
Which I do not understand.
I can only make sorting work by setting order_by in view.py:
class ResultsTable(tables.Table):
class Meta:
model = Performance
attrs = {'class': 'paleblue'}
order_by_field = True
def result(request, system):
results = Performance.objects.filter(system__name=system)
table = ResultsTable(results, order_by=('<any column name from Performance>',))
RequestConfig(request).configure(table)
return render_to_response('result.html', {'table': table})
but that obviously only works for one column and I want to click on columns to choose which one to sort by.
It is my understanding from the docs that sorting by column should work 'out of the box', is this correct, or am I doing something else wrong?
Experienced the same issue, only I was missing the
django.core.context_processors.request
from TEMPLATE_CONTEXT_PROCESSORS in settings.py
Other responses on this page point in the right direction, but just wanted to include everything required to get this working in one place. In the view:
RequestConfig
(essential - ordering won't work without this!)# views.py
from django_tables2 import RequestConfig
...
data = MyModel.objects.all()
my_table = MySummariesTable(data)
my_table.order_by = "-name"
RequestConfig(request).configure(my_table)
ctx = {"my_table": my_table}
return render(request, "path/mytemplate.html", ctx)
If any of your columns need to be orderable by foreign-key relations, define those in your table column definitions with e.g.
col1 = tables.Column(verbose_name="Some Col", order_by="mycol.foobar.name")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With