Django3 Paginator с представлением на основе функций
class ProductList(ListView):
model = Product
paginate_by = 8
def company_page(request, slug):
...
product_list = Product.objects.filter(company=company).order_by('-pk')
paginator = Paginator(product_list, 4)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
return render(request, 'product/product_list.html', {
...,
'product_list': product_list,
'page_obj': page_obj
})
views.py
<nav aria-label="Pagination">
<ul class="pagination justify-content-center my-5">
{% if page_obj.has_previous %}
<li class="page-item mx-auto lead">
<a class="page-link" href="?page={{page_obj.previous_page_number}}" tabindex="-1" aria-disabled="true">
Newer</a>
</li>
{% else %}
<li class="page-item disabled">
<a class="page-link" href="#" tabindex="-1" aria-disabled="true">
Newer</a>
</li>
{% endif %}
{% if page_obj.has_next %}
<li class="page-item mx-auto lead">
<a class="page-link" href="?page={{page_obj.next_page_number}}">
Older</a>
</li>
{% else %}
<li class="page-item disabled mx-auto lead">
<a class="page-link" href="#!">
Older</a>
</li>
{% endif %}
</ul>
</nav>
product_list.html
Пагинация хорошо работает в представлении ProductList, но не работает в представлении company_page. Кнопки Newer & Older работают, но страница продолжает показывать каждый объект списка продуктов.
Попробуйте это:
views.py
# other views ...
def company_page(request, slug):
product_list = Product.objects.filter(company=company).order_by('-pk')
page = request.GET.get('page', 1)
paginator = Paginator(product_list, 4)
try:
Products = paginator.page(page)
except PageNotAnInteger:
Products = paginator.page(1)
except EmptyPage:
Products = paginator.page(paginator.num_pages)
context = {'Products': Products}
return render(request, 'product/product_list.html', context)
product_list.html
<nav aria-label="Pagination">
{% if Products.has_other_pages %}
<ul class="pagination justify-content-center my-5">
{% if Products.has_previous %}
<li class="page-item mx-auto lead">
<a class="page-link" href="?page={{ Products.previous_page_number }}" tabindex="-1" aria-disabled="true">
Previous</a>
</li>
{% else %}
<li class="page-item disabled">
<a class="page-link" href="#" tabindex="-1" aria-disabled="true">
Previous</a>
</li>
{% endif %}
{% for i in Products.paginator.page_range %}
{% if Products.number == i %}
<li class="page-item mx-auto lead">
<a class="page-link" href="?page={{ i }}">
{{ i }}</a>
</li>
{% endif %}
{% endfor %}
{% if Products.has_next %}
<li class="page-item mx-auto lead">
<a class="page-link" href="?page={{ Products.next_page_number }}">
Next</a>
</li>
{% else %}
<li class="page-item disabled mx-auto lead">
<a class="page-link" href="#!">
Next</a>
</li>
{% endif %}
</ul>
{% endif %}
</nav>