In the view.py file, instead of passing the listings we pass paged_listings
Import from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
Here we tell how many listings to show per page paginator = Paginator(listings, 6)
You can load the all listings with orderlistings = Listing.objects.all()
You can order the listings by any field listings = Listing.objects.order_by(‘-list_date’)
You can add a filter listings = Listing.objects.order_by(‘-list_date’).filter(is_published=True)
You can limit the number of listings listings = Listing.objects.order_by(‘-list_date’).filter(is_published=True)[3]
def index(request):
listings = Listing.objects.order_by(‘-list_date’).filter(is_published=True)
paginator = Paginator(listings, 6)
page = request.GET.get(‘page’)
paged_listings = paginator.get_page(page)
context = {
‘listings’ : paged_listings
}
return render(request, ‘listings/listings.html’, context)
In the HTML page
-
{% if listings.has_previous %}
- «
- {{i}}
- {{i}}
- »
{% else%}
«
{% endif %}
{% for i in listings.paginator.page_range %}
{% if listings.paginator.page_range %}
{% if listings.number == i%}
{% else %}
{% endif%}
{% endif %}
{% endfor %}
{% if listings.has_next %}
{% else%}
»
{% endif %}
{% endif %}
Example and available methods
>>> objects = [‘john’, ‘paul’, ‘george’, ‘ringo’]
>>> p = Paginator(objects, 2)
>>> p.count
4
>>> p.num_pages
2
>>> type(p.page_range)
>>> p.page_range
range(1, 3)
>>> page1 = p.page(1)
>>> page1
>>> page1.object_list
[‘john’, ‘paul’]
>>> page2 = p.page(2)
>>> page2.object_list
[‘george’, ‘ringo’]
>>> page2.has_next()
False
>>> page2.has_previous()
True
>>> page2.has_other_pages()
True
>>> page2.next_page_number()
Traceback (most recent call last):
…
EmptyPage: That page contains no results
>>> page2.previous_page_number()
1
>>> page2.start_index() # The 1-based index of the first item on this page
3
>>> page2.end_index() # The 1-based index of the last item on this page
4
>>> p.page(0)
Traceback (most recent call last):
…
EmptyPage: That page number is less than 1
>>> p.page(3)
Traceback (most recent call last):
…
EmptyPage: That page contains no results