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

Django基于类视图的搜索结果分页问题:翻页丢失查询参数

解决分页时保留搜索关键词的问题

问题根源是Django ListView默认生成的分页链接仅携带page参数,不会自动保留搜索关键词search_query,导致翻页时该参数丢失,查询集回到全量数据。以下是具体解决步骤:

1. 在视图中传递搜索关键词到模板

修改SearchedResults类的get_context_data方法,将当前搜索关键词存入上下文,同时补充公共上下文数据(和Main视图保持一致):

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    # 把搜索关键词传递到模板
    context['search_query'] = self.request.GET.get('search_query', '')
    # 补充公共上下文内容
    context.update(get_quotes())
    return context

2. 在模板中修改分页链接,携带搜索参数

在quotes/index.html的分页区域,给每个分页URL添加search_query参数,确保翻页时参数不丢失:

{% if quotes.has_other_pages %}
  <div class="pagination">
    {% for page_num in quotes.paginator.page_range %}
      {% if quotes.number == page_num %}
        <span class="current-page">{{ page_num }}</span>
      {% else %}
        <a href="?page={{ page_num }}&search_query={{ search_query }}">{{ page_num }}</a>
      {% endif %}
    {% endfor %}
  </div>
{% endif %}

若模板中使用page_obj(ListView默认传入的分页对象),将上述代码中的quotes替换为page_obj即可。

同时,给搜索表单的输入框设置默认值,保证翻页时输入框不会被清空:

<form method="get" action="{% url 'searched_results' %}">
  <input type="text" name="search_query" value="{{ search_query }}" placeholder="输入关键词搜索...">
  <button type="submit">搜索</button>
</form>

完成以上修改后,翻页时search_query参数会被保留在URL中,视图能正确获取并过滤查询集,分页功能即可正常工作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 18:13:11