Search code examples
djangodjango-tables2

Django-tables2 does not sort


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?


Solution

  • 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...