首页 > 解决方案 > Django 分页保留当前 URL 参数

问题描述

我正在使用 Django 开发一个博客网站。在主页上,我有一个帖子列表,它们是使用分页查看的。在同一个主页上,我还具有进行文本搜索的功能(即搜索具有给定文本的帖子)。

例如,如果我搜索“hello”,则 URL 为:http://localhost:8000/?q=hello。然后,我想转到分页中的第二页,我希望 URL 看起来像这样:http://localhost:8000/?q=hello&page=2。但是,相反,我得到了这个 URL:http://localhost:8000/?page=2

因此,基本上,当我浏览页面时,我希望我的分页将现有的“q”参数保留在当前 URL 中。问题是浏览页面时“q”参数消失了。

我该如何解决?

这是我的分页:

<div class="pagination">
    <span class="step-links">
    {% if page.has_previous %}
        <a href="?page={{ page.previous_page_number }}"><i class="previous fa fa-arrow-left fa-lg"></i></a>
    {% endif %}
        <span class="current">
      {{ page.number }} of {{ page.paginator.num_pages }}
    </span>
        {% if page.has_next %}
            <a href="?page={{ page.next_page_number }}"><i class="next fa fa-arrow-right fa-lg"></i></a>
        {% endif %}
    </span>
</div>

标签: djangodjango-urlsdjango-pagination

解决方案


这是修复它的一种方法。

views.py

def your_view(request):
    ....
    query = request.GET.get('q') # Query or None
    ...
    context = {'query': query}

在 a 标签中添加{% if query %}&q={{ query }}{% endif %}

templates

<a href="?page={{ page.previous_page_number }}{% if query %}&q={{ query }}{% endif %}">
    <i class="previous fa fa-arrow-left fa-lg"></i>
</a>

推荐阅读