Reputation: 2748
I am looking at A.Mele Django by Example,chapter1
def post_list(request, category=None):
object_list = Post.published.all()
paginator = Paginator(object_list, 3) # 3 posts in each page
page = request.GET.get('page')
try:
posts = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer deliver the first page
posts = paginator.page(1)
except EmptyPage:
# If page is out of range deliver last page of results
posts = paginator.page(paginator.num_pages)
return render(request, 'blog/post/list.html', {'page': page,
'posts': posts})
This line that gets page is what I really do not understand.
page = request.GET.get('page')
Get method sends user information with the request. But what is get actually doing? This is blog/post/list.html
{% extends "blog/base.html" %}
{% block title %}My blog{% endblock %}
{% block content %}
{% include "pagination.html" with page=posts %}
<h1>My Blog</h1>
{% for post in posts %}
<h2>
<a href="{{ post.get_absolute_url }}">{{ post.title }}</a>
</h2>
<p class="date">
Published {{ post.publish }} by {{ post.author }}
</p>
{{ post.body|truncatewords:30|linebreaks }}
{% endfor %}
{% endblock %}
Upvotes: 2
Views: 3530
Reputation: 477284
In a URL you can send parameters. For example:
https://www.example.com/some/path/foo.html?key1=val1&key2=val2
The part in boldface contains two parameters: key1
and key2
, and the values are val1
and val2
respectively.
The request.GET
decodes these parameters and stores it in a QueryDict
. This is basically some sort of dictionary (but a key can map to multiple values).
We here thus look for a ?page=1
parameter, and obtain this with request.GET.get('page')
. In case no such parameter is given, None
is returned.
We can use this for pagination, since a page can for example contain URLs for the next and previous page, where the ?page=
parameter, will be incremented or decremented.
The base.html
therefore probably contains some logic that generates links with on the second page links to ?page=1
and ?page=3
that thus link to the same URL, but with different parameters. Django then decodes these parameters, and paginates the queryset accordingly.
Usually one encodes parameters in the URL in case the URL has no side-effects (meaning no significant data in the database changes). The advantage of encoding data in the URL is that if you for example share a URL to a friend, he/she will see the same pagination (and therefore the page will not per se display the first blogpost).
This is in contrast to URLs that are for example used to log in or to perform certain effects: then the data is typically encoded in the request headers. As a result you will not share sensitive data to a person with which you share the URL, and making the request a second time typically has no effects.
Upvotes: 10