我正在根据用户选择获取查询结果,并将其显示在Django的引导卡中。我正在使用django Paginator在每页上最多显示6个结果(当前设置为1以进行测试)。问题是我的分页器在所有分页页面上显示了所有结果。
有人可以帮我吗?
查看:
def results(request):
results = []
query_city = request.GET.get('city')
print(query_city)
all_records = hotel.objects.all()
for states in all_records:
if states.confirm_approval and states.space_state == query_city:
print(states)
results.append(states)
paginator = Paginator(results,1)
page = request.GET.get('page')
try:
items = paginator.page(page)
except PageNotAnInteger:
items = paginator.page(1)
except EmptyPage:
items = paginator.page(paginator.num_pages)
index = items.number - 1
max_index = len(paginator.page_range)
start_index = index - 5 if index >= 5 else 0
end_index = index + 5 if index <= max_index - 5 else max_index
page_range = paginator.page_range[start_index:end_index]
context = {
'results':results,
'items':items,
'page_range':page_range,
}
return render(request, 'results/results.html', context)
HTML模板:
% for result in results %}
{% if forloop.counter0|divisibleby:3 %} <div class="row"> {% endif %}
<div class="col">
<div class="card-deck" id="cardholder">
<div class="card" style="max-width: 20rem;">
<img class="card-img-top" src="{% static 'mainpage/img/bg/books.jpg' %}" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">{{ result.hotel_name }}</h5>
</div>
<div class="card-footer">
<a href="#" class="btn btn-primary">Show more</a>
</div>
</div>
</div>
</div>
{% if forloop.counter|divisibleby:3 or forloop.last %}</div><!-- row closing -->{% endif %}
{% endfor %}
{% if items.has_other_pages %}
<nav aria-label="">
<ul class="pagination justify-content-center">
{% if items.has_previous %}
<li class=class="page-item">
<a class="page-link"
href="?page={{items.previous_page_number}}{% if request.GET.city %}&city={{ request.GET.city }}{% endif %}"
tabindex="-1">Previous</a>
</li>
{% else %}
<li class="page-item disabled"><a class="page-link">Previous</a></li>
{% endif %}
{% for i in page_range %}
{% if items.number == i %}
<li class="page-item active"><a class="page-link" href="#">{{i}} <span
class="sr-only">(current)</span></a>
</li>
{% else %}
<li class="page-item"><a class="page-link"
href="?page={{i}}{% if request.GET.city %}&city={{ request.GET.city }}{% endif %}">{{i}}</a>
</li>
{% endif %}
{% endfor %}
{% if items.has_next %}
<li class="page-item">
<a class="page-link" aria-label="Next"
href="?page={{items.next_page_number}}{% if request.GET.city %}&city={{ request.GET.city }}{% endif %}">Next</a>
</li>
{% else %}
<li class="page-item disabled"><a class="page-link">Next</a></li>
{% endif %}
</ul>
</nav>
{% endif %}
答案 0 :(得分:0)
brtt3000帮助我进行了重做。
这是他的答案:您正在遍历错误的上下文变量, 更改为项目。
{%代表结果%%}我一看到您就怀疑了 在上下文中都是项目和结果:)
对于到达这里的任何人,请记住传递分页变量。