查找键失败 - 使用 elided_page 实现分页

Failed lookup for key - implementing pagination with elided_page

我正在尝试基于此 blog post 使用 elided_page 实现分页。我的目标是分页,只显示几页,并随着查看新页面而增加,因为我最终将有超过一百页。

查看

def home(request):

page = request.GET.get('page', 1)
paginator = Paginator(Post.objects.all(), 2)
page_range = paginator.get_elided_page_range(number=page)

context = { 'page_range':page_range, 'page':page, 'paginator':paginator}

return render(request, 'blog/home.html', context)

模板

<ul class="pagination justify-content-center flex-wrap mt-2 mb-4">
{% if page_obj.has_previous %}
    <li class="page-item"><a class="page-link" href="?page={{ page_obj.previous_page_number }}">&laquo;</a></li>
{% else %}
    <li class="disabled page-item"><span class="page-link">&laquo;</span></li>
{% endif %}
{% for i in page_range|default_if_none:page_obj.paginator.get_elided_page_range %}
    {% if page_obj.number == i %}
        <li class="active page-item"><span class="page-link">{{ i }} <span class="sr-only">(current)</span></span>
        </li>
    {% else %}
        {% if i == page_obj.paginator.ELLIPSIS %}
            <li class="page-item"><span class="page-link">{{ i }}</span></li>
        {% else %}
            <li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li>
        {% endif %}
    {% endif %}
{% endfor %}
{% if page_obj.has_next %}
    <li class="page-item"><a class="page-link" href="?page={{ page_obj.next_page_number }}">&raquo;</a></li>
{% else %}
    <li class="disabled page-item"><span class="page-link">&raquo;</span></li>
{% endif %}

然而当我运行这个我得到错误

Failed lookup for key [page_obj] in [{'True': True, 'False': False, 'None': None}, {}, {}, {'page_range': <generator object Paginator.get_elided_page_range at 0x000001FB70D20E40>, 'page': '3', 'paginator': <django.core.paginator.Paginator object at 0x000001FB70D7A490>}]

这条线

{% for i in page_range|default_if_none:page_obj.paginator.get_elided_page_range %}

如果我编辑该行并将其设置为 {% for i in page_range %} 它可以工作,但显示的每一页都会让我相信错误出在声明的这一部分 |default_if_none:page_obj.paginator.get_elided_page_range

我不太擅长使用模板,但在我的研究中,我遇到了这个 . Where a user was experiencing a similar issue and say that this is just a bug in django,它不会被修复。这是真的?如果不是,我将如何解决这个问题,或者我只是以错误的方式解决这个问题。

实际页面似乎没有经过处理并且丢失了。

尝试添加这一行:

page_obj = paginator.get_page(page)

并将其传递给上下文。所以完整的视图是:

def home(request):
    page = request.GET.get('page', 1)
    paginator = Paginator(Post.objects.all(), 2)
    page_obj = paginator.get_page(page)
    page_range = paginator.get_elided_page_range(number=page)

    context = {'page_range': page_range, 'page': page, 'paginator': paginator, 'page_obj': page_obj}

    return render(request, 'blog/home.html', context)