【发布时间】:2019-09-23 20:05:55
【问题描述】:
我使用 Django 制作了一个过滤器表单,它返回一个分页匹配列表。
当我最初运行过滤器时,我得到了正确的显示页数。但是,当我单击另一个页码时,该页面将恢复为未过滤结果的相关页码。例如,我过滤了“Bug”上的结果,并获得了“Bug”类型的工单的所有分页结果。分页显示指向不同页面(1、2、3 等)的链接以及下一个和最后一个按钮。但是,如果我单击“3”,结果将恢复为未过滤的结果,我将获得未过滤结果的第 3 页而不是过滤结果的第 3 页的结果,以及未过滤结果的总页数显示在分页链接中。
请任何人帮助我了解如何解决问题并在浏览分页时保留过滤结果?
all_tickets.html:
// filter form code //
// Displayed results (unfiltered results displayed when page is first loaded) //
<!-- Pagination - only visible if there are multiple pages -->
{% if tickets.has_other_pages %}
<ul class="pagination center-align">
<!-- Previous/First button - only visible if previous page available -->
{% if tickets.has_previous %}
<!-- First page button -->
<li>
<a href="?page=1">
<i class="fas fa-angle-double-left" aria-hidden="true"></i>
</a>
</li>
<!-- Previous page button -->
<li>
<a href="?page={{ tickets.previous_page_number }}">
<i class="fas fa-angle-left" aria-hidden="true"></i>
</a>
</li>
{% endif %}
<!-- Show link to current page and only few other surrounding pages, not all -->
{% for num in tickets.paginator.page_range %}
<!-- Show the current page number but disable it -->
{% if tickets.number == num %}
<li class="disabled">
<a>
{{ num }}
</a>
</li>
<!-- Show the 4 surrounding (2 next and 2 previous) pages -->
{% elif num > tickets.number|add:'-3' and num < tickets.number|add:'3' %}
<li>
<a href="?page={{ num }}">
{{ num }}
</a>
</li>
{% endif %}
{% endfor %}
<!-- Next/Last button - only visible if previous page available -->
{% if tickets.has_next %}
<!-- Next page button -->
<li>
<a href="?page={{ tickets.next_page_number }}">
<i class="fas fa-angle-right" aria-hidden="true"></i>
</a>
</li>
<!-- Last page button -->
<li>
<a href="?page={{ tickets.paginator.num_pages }}">
<i class="fas fa-angle-double-right" aria-hidden="true"></i>
</a>
</li>
{% endif %}
</ul>
{% endif %}
在 views.py 文件中搜索视图:
def view_all_tickets(request):
'''
View all tickets
Allows users to filter tickets based on type or status
'''
tickets = Ticket.objects.all()
page = request.GET.get('page', 1)
ticket_type_dropdown = TicketType.objects.all()
ticket_status_dropdown = TicketStatus.objects.all()
# Query parameters
ticket_type = request.GET.get("ticket_type")
ticket_status = request.GET.get("ticket_status")
# Filter by query parameters
if ticket_type:
tickets = tickets.filter(ticket_type__id=ticket_type)
else:
tickets
if ticket_status:
tickets = tickets.filter(ticket_status__id=ticket_status)
else:
tickets
# Pagination
paginator = Paginator(tickets, 1)
try:
tickets = paginator.page(page)
except PageNotAnInteger:
tickets = paginator.page(1)
except:
tickets = paginator.page(paginator.num_pages)
args = {
"tickets": tickets,
"ticket_type_dropdown": ticket_type_dropdown,
"ticket_status_dropdown": ticket_status_dropdown,
}
return render(request, "all_tickets.html", args)
【问题讨论】:
标签: python django filter pagination