Python/Django
페이지네이션
happyso
2020. 8. 11. 10:21
https://docs.djangoproject.com/en/3.0/topics/pagination/
Pagination | Django documentation | Django
Django The web framework for perfectionists with deadlines. Overview Download Documentation News Community Code Issues About ♥ Donate
docs.djangoproject.com
1. html파일 생성
[pagination.html]
<nav aria-label="Page navigation example" >
<ul class="pagination">
<li class="page-item">
{% if page.has_previous %}
<a class="page-link" href="?page={{page.previous_page_number}}">Previous</a>
{% endif %}
</li>
<li class="page-item">
<a class="page-link">Page {{page.number}} of {{page.paginator.num_pages}}</a>
</li>
<li class="page-item">
{% if page.has_next %}
<a class="page-link" href="?page={{page.next_page_number}}">Next</a>
{% endif %}
</li>
</ul>
</nav>
2. Python Console 창 명령어 입력을 통해 먼저 연습해본다.
from django.core.paginator import Paginator
objects = ['aa','bb','cc','dd','ee']
objects
#['aa', 'bb', 'cc', 'dd', 'ee']
paginator = Paginator(objects,2)
paginator.count
#5
paginator.num_pages
#3
paginator.page_range
#range(1, 4)
page1 = paginator.page(1)
page1
#<Page 1 of 3>
page1.object_list
#['aa', 'bb']
page2 = paginator.page(2)
page2.object_list
#['cc', 'dd']
page2
#<Page 2 of 3>
page3 = paginator.page(3)
page3.object_list
#['ee']
page1.has_next()
#True
page2.has_previous()
#True
page2.next_page_number()
#3
page3.start_index()
#5
page3.end_index()
#5
3. Views.py 수정
- import추가
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
- def post_list 수정
def post_list(request):
# posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
# return render(request, 'blog/post_list.html', {'posts': posts})
post_list = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
paginator = Paginator(post_list, 2)
page = request.GET.get('page')
try:
posts = paginator.page(page)
except PageNotAnInteger:
posts = paginator.page(1)
except EmptyPage:
posts = paginator.page(paginator.num_pages)
return render(request, 'blog/post_list.html', {'posts': posts})
4. post_list.html 수정
- {% include 'blog/pagination.html' with page=posts %} 추가
{% extends 'blog/base.html' %}
{% block content%}
{% for post in posts %}
<div class="post">
<div class="date">
<p>published : {{post.published_date}}</p>
</div>
<h1><a href="{% url 'post_detail_test' pk=post.pk %}">{{post.title}}</a></h1>
<a href="{% url 'post_detail_test' pk=post.pk %}">Comments: {{post.approved_comments.count}}</a>
</div>
{% empty %}
<div>요청하신 Post가 존재하지 않습니다. </div>
{% endfor %}
{% include 'blog/pagination.html' with page=posts %}
{% endblock %}