You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django分页器跳转时无法携带filter过滤器查询参数问题求解

解决方案

错误原因说明

你之前自定义标签报错的核心原因是:Django的自定义标签不能直接写在视图文件中,必须放在应用下专门的templatetags目录中才能被识别加载。

实现步骤

1. 配置自定义标签库

在你存放views.py的应用根目录下,新建名为templatetags的文件夹,和views.py、models.py保持同级。在该文件夹下新建两个文件:

  • 空文件__init__.py,用来标记该目录为Python包
  • 新建page_tags.py,写入如下代码:
from django import template
register = template.Library()

@register.simple_tag
def url_replace(request, field, value):
    query_dict = request.GET.copy()
    query_dict[field] = str(value)
    return query_dict.urlencode()

完成后重启Django开发服务器,新的标签库才能被识别。

2. 模板加载标签

在分页器所在模板的最顶部,添加标签加载语句:

{% load page_tags %}

3. 替换所有分页链接

将分页模板中所有分页相关的链接全部替换为携带现有查询参数的格式,修改后的完整分页模板代码如下:

<nav aria-label="Page navigation example" class="paginator">
    <ul class="pagination justify-content-center">
        <li class="page-item">
            {% if page_obj.has_previous %}
            <a class="page-link" href="?{% url_replace request 'page' page_obj.previous_page_number %}" aria-label="Previous">
                <span aria-hidden="true">&laquo;</span>
            </a>
            {% else %}
        </li>
        <li class="page-item disabled">
            <a class="page-link" href="#" aria-label="Previous">
                <span aria-hidden="true">&laquo;</span>
            </a>
        </li>
        {% endif %}
        {% for i in page_range %}
            {% if page_obj.number == i %}
            <li class="page-item active" aria-current="page">
                <a class="page-link" href="#">{{ i }}</a>
            </li>
            {% elif i > page_obj.number|add:'-3' and i < page_obj.number|add:'3' %}
            <li class="page-item"><a class="page-link" href="?{% url_replace request 'page' i %}">{{ i }}</a></li>
            {% endif %}
        {% endfor %}
        <li class="page-item">
            {% if page_obj.has_next %}
            <a class="page-link" href="?{% url_replace request 'page' page_obj.next_page_number %}" aria-label="Next">
                <span aria-hidden="true">&raquo;</span>
            </a>
            {% else %}
        </li>
        <li class="page-item disabled">
            <a class="page-link" href="#" aria-label="Next">
                <span aria-hidden="true">&raquo;</span>
            </a>
        </li>
        {% endif %}
    </ul>
</nav>

可选简化方案(Django 3.2+版本适用)

如果你的Django版本≥3.2,不需要写自定义标签,直接使用内置的querystring标签即可,会自动保留现有查询参数,只更新指定的页码字段:

{# 上一页链接示例 #}
<a class="page-link" href="?{% querystring page=page_obj.previous_page_number %}" aria-label="Previous">

{# 中间页码链接示例 #}
<a class="page-link" href="?{% querystring page=i %}">{{ i }}</a>

{# 下一页链接示例 #}
<a class="page-link" href="?{% querystring page=page_obj.next_page_number %}" aria-label="Next">

内容的提问来源于stack exchange,提问作者Wazy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 07:09:01