Django: django-tables2 pagination and filtering

Viewed 13754

I have a working table generated by django-tables2:

my_filter = TestFilter(request.POST) 
table = TestTable(TestObj.objects.all(), order_by="-my_date")
RequestConfig(request, paginate={"per_page": 10}).configure(table)
return render(request, 'test_app/index.html', {'table': table, 'my_filter': my_filter})

The above code returns a table with hundreds of objects that are neatly paginated with 10 items per page. When I click "Next" at the bottom of the table, pagination works well and I can navigate through different pages. However, I noticed the following behavior:

  • Click on my_filter which displays a subset of the original unfiltered table
  • Click "Next" on the bottom of the filtered table will result in displaying the 2nd page of the unfiltered table
  • Click on my_filter again displays the 2nd page of the filtered table

I would like the filter to persist while navigating different pages. I found a similar question here. That solution indicates that the html code needs to be altered. However, in my case django-tables2 is generating the html.

How can I correctly implement pagination with filtering using django-tables2?

-Update-

I've tried using GET instead of POST:

if request.method == 'GET':
    my_filter = TestFilter(request.GET)
    my_choice = my_filter.data['my_choice']
    table = TestTable(TestObj.objects.filter(choice=my_choice), order_by="-my_date")
    RequestConfig(request, paginate={"per_page": 10}).configure(table)
    return render(request, 'test_app/index.html', {'table': table, 'my_filter': my_filter})

My template:

<form action="" method="get"> {% csrf_token %}
    {{ my_filter }} <input type="submit" value="Apply Filter"/>
</form>

This results in a KeyError due to my_choice not existing in GET. As a result the page does not even load.

1 Answers
Related