Search code examples
django-tables2

dynamically set per_page in django-tables2


Websites often allow the user to specify how many items to show per page in a paginated table. Iwould like to do this with django-tables2.

I could add a "Show [ 5 | 10 | 50 ] per page" select box to collect a per_page parameter from the user.

However, the "Previous" and "Next" buttons in the table template are hyperlinks, with a hardcoded value for per_page, e.g.:

<a href="?per_page=5&page=5">Next</a>

I am thinking the only way to make this dynamic would be to use javascript, e.g.:

<span onclick="get_table_page(5)">Next</span>

Where the functions get_table_page() can retrieve the per_page parameter from the select box.

Is that the best way to do it? Or is there a way without javascript?

UPDATE: No answer to the question (how to change per_page for Previous/Next page) but, as accepted answer points out, user can reload the current page with changed per_page parameter, e.g.:

<p>Show [ <a href="{% querystring "per_page"=5  %}">5</a>
        | <a href="{% querystring "per_page"=20 %}">20</a>
        | <a href="{% querystring "per_page"=50 %}">50</a>
        ] Items</p>

With thanks and best wishes

Ivan


Solution

  • django-tables2 supports the per_page keyword argument to table.paginate(). If RequestConfig or one of the class based views is used, just adding per_page=20 to the url will make django-tables2 re-render with 20 rows per page.

    You can create urls in your custom template using the {% querystring per_page=20 %} tag, which should keep the sorting/filtering intact.