<img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=338168267432629&amp;ev=PageView&amp;noscript=1">
Programming

django-sorting

There is also an easy way to sort tabular data this time using django-sorting (https://github.com/directeur/django-sorting). Setup is described in the project’s readme and is as simple as putting the app in your installed apps and middleware and adding the request template context processor. After that, it’s as simple as this: …


There is also an easy way to sort tabular data this time using django-sorting (https://github.com/directeur/django-sorting). Setup is described in the project’s readme and is as simple as putting the app in your installed apps and middleware and adding the request template context processor. After that, it’s as simple as this:

 

    
    <table>
        <thead>
            <tr>
                <th></th>
                <th></th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            
        </tbody>
    </table>

The sorting tags are autosort and anchor.

This results in a following table, sortable by its headers. This one is sorted descending by first name:

 

However, we again run into the problem of the table being too long. It’s a good thing django-sortable works well with django-pagination:

 

    
    
    <table>
        <thead>
            <tr>
                <th></th>
                <th></th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            
        </tbody>
    </table>
    

Be sure to call autosort before autopaginate as the queryset needs to be ordered before it’s sliced. This results in a table that is both sortable and paginated:

 

django-sorting has the same limitation as django-pagination: it can’t be used more than once in the same page. If you try to do so and sort by a column, the column should be in all querysets that are autosorted otherwise an error will be thrown (it tries to sort it on a column it doesn’t have). It will work for multiple tables in the same page as long as you sort on columns with the same name and you’re alright with all the tables being sorted on the same column.

Similar posts

Get notified about the latest in Tech

Be the first to know about new tech from the experts at Bixly!