sebam2k4
4/3/2018 - 6:09 PM

Django 1.11 Pagination with Bootstrap 4.0

Django 1.11 Pagination with Bootstrap 4.0

from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

def product_list(request):
  """
  Returns a paginated list of product objects and renders them
  to the product_list.html template
  """
  product_list = Product.objects.all()

  # paginate the product list
  paginator = Paginator(object_list=products_list, per_page=9)
  products_page = request.GET.get('page')
  try:
    products = paginator.page(products_page)
  except PageNotAnInteger:
    # if page is not an integer, deliver first page
    products = paginator.page(1)
  except EmptyPage:
    # deliver last page of results when page is out of range
    products = paginator.page(paginator.num_pages)

  context = {'products': products, 'paginator': paginator}
  return render(request, 'product_list.html', context)
{% for product in products %}
<!-- html for your product list -->
{% endfor %}

{# Pagination #}
<nav aria-label="pagination">
  <ul class="pagination justify-content-center">
    {% if products.has_previous %}
    <li class="page-item">
      <a class="page-link" href="?page={{ products.previous_page_number }}" aria-label="Previous">
        <span aria-hidden="true">&laquo;</span>
        <span>Previous</span>
      </a>
    </li>
    {% endif %}
    {% if products.has_previous or products.has_next %}
      {% for num in paginator.page_range %}
        {% if products.number == num %}
        <li class="page-item active page-link">{{ num }} <span class="sr-only">(current)</span></li>
        {% else %}
        <li class="page-item active"><a class="page-link" href="#">{{ num }}<span class="sr-only">(current)</span></a></li>
        {% endif %}
      {% endfor %}
    {% endif %}
    {% if products.has_next %}
    <li class="page-item">
      <a class="page-link" href="?page={{ products.next_page_number }}" aria-label="Next">
          <span>Next</span>
        <span aria-hidden="true">&raquo;</span>
      </a>
    </li>
    {% endif %}
  </ul>
</nav>