使用 ListView 显示分页结果的最后一页而不是 404 [英] Display last page of paginated results instead of 404 using ListView
问题描述
Django docs 展示如何通过捕获 EmptyPage
异常,使用基于函数的视图返回分页查询集的最后一页.
The Django docs show how to return the last page of a paginated queryset using a function-based view by catching the EmptyPage
exception.
使用基于类的通用视图(例如 ListView
)实现相同目标的最简单方法是什么?
What's the easiest way to achieve the same thing using generic class-based views, for example ListView
?
我首先想到的是 allow_empty
设置 MultipleObjectMixin
可以满足我的需求,但检查代码表明它只能防止 404如果查询集中的对象为零,而不是请求的页面上的对象为零,则会出错.
I first thought that the allow_empty
setting for MultipleObjectMixin
would do what I need, but examining the code shows that it only prevents a 404 error if there are zero objects in the queryset, rather than zero objects on the page requested.
两个选项似乎是:
- 子类
ListView
并覆盖paginate_queryset
(继承自MultipleObjectMixin
),或 - subclass
Paginator
并覆盖validate_number
,并将paginator_class
设置为视图中的子类.
- subclass
ListView
and overridepaginate_queryset
(inherited fromMultipleObjectMixin
), or - subclass
Paginator
and overridevalidate_number
, and setpaginator_class
to the subclass in the view.
有没有更好的方法来实现这一目标?
Is there a better way to achieve this?
推荐答案
这是选项 2 的样子:
Here's what option 2 looks like:
from django.core.paginator import EmptyPage, Paginator
from django.views.generic import ListView
class SafePaginator(Paginator):
def validate_number(self, number):
try:
return super(SafePaginator, self).validate_number(number)
except EmptyPage:
if number > 1:
return self.num_pages
else:
raise
class MyView(ListView):
paginator_class = SafePaginator
paginate_by = 25
[...]
这对我来说似乎是目前最好的选择.
This seems like the best option to me at the moment.
这篇关于使用 ListView 显示分页结果的最后一页而不是 404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!