Django 分页保持当前 URL 个参数

Django Pagination Keep Current URL Parameters

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

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

所以,基本上,当我浏览页面时,我希望我的分页保留当前 URL 中现有的“q”参数。问题是在浏览页面时“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>

这是修复它的一种方法。

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>