Question

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?

Was it helpful?

Solution 2

Found the answer to my own question, after a night of sleep and a fresh look and word-by-word comparison of my code with the examples in the django-tables2 docs.

For the result function I used:

return render_to_response('result.html', {'table': table})

If I replace that with:

return render(request, 'result.html', {'table': table})

Sorting works as expected. Don't ask me why...

OTHER TIPS

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:

  1. Define your queryset without ordering
  2. Pass the queryset into the table instance
  3. Set any customizations on the table obj, like default ordering
  4. Wrap it all in RequestConfig (essential - ordering won't work without this!)
  5. Pass the fully-configured table into template context
# 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")

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top