【问题标题】:Django Pagination Keep Current URL ParametersDjango 分页保留当前 URL 参数
【发布时间】:2020-10-23 18:20:07
【问题描述】:

我正在使用 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>

【问题讨论】:

  • 可以提供查看功能吗?

标签: django django-urls django-pagination


【解决方案1】:

这是修复它的一种方法。

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>

【讨论】:

    猜你喜欢
    • 2010-11-28
    • 2012-03-28
    • 1970-01-01
    • 1970-01-01
    • 2015-02-15
    • 2015-10-03
    • 1970-01-01
    • 1970-01-01
    • 2015-09-26
    相关资源
    最近更新 更多