使用 ListView 显示分页结果的最后一页而不是 404 [英] Display last page of paginated results instead of 404 using ListView

查看:17
本文介绍了使用 ListView 显示分页结果的最后一页而不是 404的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

两个选项似乎是:

  1. 子类ListView并覆盖paginate_queryset(继承自MultipleObjectMixin),或
  2. subclass Paginator 并覆盖 validate_number,并将 paginator_class 设置为视图中的子类.
  1. subclass ListView and override paginate_queryset (inherited from MultipleObjectMixin), or
  2. subclass Paginator and override validate_number, and set paginator_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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆