Reputation: 9782
I am working with Django's built in Pagination and figured out how to functionally use it via the Django Documentation on Pagination. Despite the fact that I am able to make it work with my app, there is a part of the example logic displayed on the documentations example that I find important to understand well before moving on. They don't explain it that well and I am not finding any other questions on StackOverflow (or the internet) that address it.
The view file example given for Django Pagination...
This example assumes class 'Contact' has already been imported.
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render
def listing(request):
contact_list = Contacts.objects.all()
paginator = Paginator(contact_list, 25) # Show 25 contacts per page
page = request.GET.get('page')
try:
contacts = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
contacts = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
contacts = paginator.page(paginator.num_pages)
return render(request, 'list.html', {'contacts': contacts})
The portion of this code that I would like explained (found in the view file)...
page = request.GET.get('page')
What is the significance of ('page')
? I can't figure it out.
Here is the template file (incase it helps with understanding...
{% for contact in contacts %}
{# Each "contact" is a Contact model object. #}
{{ contact.full_name|upper }}<br />
...
{% endfor %}
<div class="pagination">
<span class="step-links">
{% if contacts.has_previous %}
<a href="?page={{ contacts.previous_page_number }}">previous</a>
{% endif %}
<span class="current">
Page {{ contacts.number }} of {{ contacts.paginator.num_pages }}.
</span>
{% if contacts.has_next %}
<a href="?page={{ contacts.next_page_number }}">next</a>
{% endif %}
</span>
</div>
Upvotes: 0
Views: 179
Reputation: 309049
In the links, you are using page
as the variable to store the page number, for example
<a href="?page={{ contacts.previous_page_number }}">
In the rendered template, this will be be something like
<a href="?page=5">
When the use clicks on this link, then page=5
will be included in the GET parameters for the request. The page number is then fetched in the view with:
page = request.GET.get('page')
There is nothing special about the chosen variable page
. The important thing is that the string used in request.GET.get()
is the same as that used in the template.
Upvotes: 2