【发布时间】:2014-01-02 15:37:11
【问题描述】:
我有一个由 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})
上面的代码返回一个包含数百个对象的表格,这些对象整齐地分页,每页有 10 个项目。当我单击表格底部的“下一步”时,分页效果很好,我可以浏览不同的页面。但是,我注意到以下行为:
- 点击
my_filter,它会显示原始未过滤表的子集 - 点击过滤后表格底部的“下一步”会显示未过滤表格的第二页
- 再次点击
my_filter会显示过滤表的第二页
我希望过滤器在浏览不同页面时保持不变。我发现了一个类似的问题here。该解决方案表明需要更改 html 代码。但是,在我的情况下,django-tables2 正在生成 html。
如何使用 django-tables2 正确实现分页过滤?
-更新-
我尝试过使用 GET 而不是 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})
我的模板:
<form action="" method="get"> {% csrf_token %}
{{ my_filter }} <input type="submit" value="Apply Filter"/>
</form>
由于my_choice 在 GET 中不存在,这会导致 KeyError。结果页面甚至没有加载。
【问题讨论】:
标签: python django django-tables2