django - 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>
解决方案
这是修复它的一种方法。
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>
推荐阅读
- multidimensional-array - 在空间数据库中查找 K 个最近的对(无特定查询对象)
- java - 杰克逊 JsonDeserializer stackoverflow
- r - 将数据排序到由 R 中的 hclust() 创建的现有集群中
- excel - 具有多个多维数据集的 Excel 多维数据集值
- vue.js - 如何删除 vue cli 2?
- numbers - 翻译 Sap Fiori 启动板磁贴编号单位
- django - 如何使用 django 使用 datefield 检索数据?
- spring-integration - 如何在 Spring 集成测试中调用通道
- laravel - 拉拉维尔 | 获取列的值
- angular - 如何从 Eclipse Oxygen 中卸载 Angular IDE 插件?