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

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

问题描述

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.

似乎有两个选择:

  1. 子类 ListView 并覆盖 paginate_queryset (继承自 MultipleObjectMixin ),或者
  2. 子类 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如下所示:

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天全站免登陆