[Django]-Where does the "page" GET parameter come from?

3👍

When there are no parameters in the request (when you hit http://localhost:8000 directly), the value of page will be None. That is the default behaviour of request.GET.get() when it can’t find the key you’re asking for – the same as a normal Python dictionary (because GET extends it).

# page will be None
page = request.GET.get("page")

This means that None is passed to paginator.page():

try:
    # Passing None here
    posts = paginator.page(page)
except PageNotAnInteger:

Which likely means (although we can’t see the code of paginagor) that a PageNotAnInteger exception is raised, and thus a value of 1 is passed to paginagor.page():

try:
    posts = paginator.page(page)  # Raises PageNotAnInteger because None passed
except PageNotAnInteger:
    # Posts are retrieved for page 1
    posts = paginator.page(1)

The posts from the above call, and the value of page (still None) are then passed to the template.

return render(request, "post/list.html", {"page": page, "posts": posts});

The template list.html then iterates the posts and displays them.

Rather confusingly, when the pagination.html template is included, it defines a context variable called page to the current value of posts:

<!-- Pass the value of posts using a variable name of page -->
{% include "pagination.html" with page=posts %}

So the places where the pagination.html template refers to page, it is actually using the value of posts.

<!-- Really posts.number and posts.paginator.num_pages -->
Page {{ page.number }} of {{ page.paginator.num_pages }}

Hope that helps to explain things.

One other thing, you don’t need to add a semi-colon to the end of every line in Python.

Leave a comment