尝试:
def get(self, request, *args, **kwargs):
try:
return super(MyView, self).get(request, *args, **kwargs)
except Http404:
if kwargs['page'] > self.paginator.num_pages:
return HttpResponseRedirect(reverse('this_view_paged', kwargs={'page': self.paginator.num_pages}))
else:
# re-raise Http404, as the reason for the 404 was not that maximum pages was exceeded
raise Http404(_(u"Empty list and '%(class_name)s.allow_empty' is False.")
% {'class_name': self.__class__.__name__})
更新
对不起。我真的以为 Django 添加paginator
为实例变量。没有它真的很糟糕,因为它使这比它需要的困难100倍。分页器被隐藏在 中paginate_queryset
,这实际上是从那里Http404
得到的。这意味着,你甚至不能调用这个方法来获取你的分页器,因为你从中得到的只是一个异常。所以,你必须更深入,不幸的是重复了一些 Django 视图逻辑,我讨厌这样做,但这是我能看到的唯一前进道路。由于我们正在诉诸代码重复,无论如何,我现在要覆盖整个paginate_queryset
方法。新代码直接从 Django 源代码复制而来,并在注释部分中注明了修改(我为后代保留了上面的原始代码):
def paginate_queryset(self, queryset, page_size):
"""
Paginate the queryset, if needed.
"""
paginator = self.get_paginator(queryset, page_size, allow_empty_first_page=self.get_allow_empty())
page = self.kwargs.get('page') or self.request.GET.get('page') or 1
try:
page_number = int(page)
except ValueError:
if page == 'last':
page_number = paginator.num_pages
else:
raise Http404(_(u"Page is not 'last', nor can it be converted to an int."))
try:
page = paginator.page(page_number)
# Moving this line after the try/except block because DRY
#return (paginator, page, page.object_list, page.has_other_pages())
except InvalidPage:
# This used to raise a 404, but we're replacing this functionality
#raise Http404(_(u'Invalid page (%(page_number)s)') % {
# 'page_number': page_number
#})
page = paginator.page(paginator.num_pages)
return (paginator, page, page.object_list, page.has_other_pages())