使用ListView显示分页结果的最后一页而不是404 [英] Display last page of paginated results instead of 404 using ListView
问题描述
Django 文档通过捕获 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
?
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
),或者 - 子类
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如下所示:
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屋!