728x90
Paginator를 활용한 페이징(paging)
views.py
from django.shortcuts import render
from book.models import BookInfo
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
...
def show_all_book(request):
# 전체 도서를 반환
all_book = BookInfo.objects.all()
# 페이징
page = request.GET.get('page')
paginator = Paginator(all_book, 10) # 한 페이지에 10레코드씩 표시
try:
page_obj = paginator.page(page)
except PageNotAnInteger:
page = 1 # 페이지 정보가 없는 경우 첫 페이지를 표시
page_obj = paginator.page(page)
except EmptyPage:
page = paginator.num_pages # 마지막 페이지를 접속
page_obj = paginator.page(page)
# 현재 페이지를 기준으로 총 5개의 페이지만 표시
left_index = (int(page) - 2)
if left_index < 1:
left_index = 1 # 최솟값은 1로 설정
right_index = (int(page) + 2)
if right_index > paginator.num_pages:
right_index = paginator.num_pages # 최댓값은 최대페이지수로 설정
custom_range = range(left_index, right_index+1) # 마지막 숫자도 포함(+1)
context = {
"all_book" : all_book,
"page_obj" : page_obj,
"paginator" : paginator,
"custom_range" : custom_range,
}
return render(request, "book/show_all_book.html", context)
show_all_book.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>전체 도서목록</title>
</head>
<body>
<h1>전체 도서목록</h1>
...
<!-- 페이징 start-->
{% if page_obj.has_other_pages %}
<!-- 이전 -->
{% if page_obj.has_previous %}
<a style="color: blue;" href="?page={{ page_obj.previous_page_number }}">❮ 이전</a>
{% endif %}
<!-- 페이징 -->
{# {% for page in paginator.page_range %} #}
{% for page in custom_range %}
{% if page == page_obj.number %}
<a style="color:red;" href="?page={{ page }}">{{ page }}</a>
{% else %}
<a style="color:blue;" href="?page={{ page }}">{{ page }}</a>
{% endif %}
{% endfor %}
<!-- 다음 -->
{% if page_obj.has_next %}
<a style="color: blue;" href="?page={{ page_obj.next_page_number }}">다음 ❯</a>
{% endif %}
{% endif %}
<!-- 페이징 end-->
</body>
</html>
728x90
'03_Web' 카테고리의 다른 글
[Django]부트스트랩(Bootstrap)을 활용한 form디자인 (1) | 2025.05.27 |
---|---|
[Django]로그인 기능 구현 (4) | 2025.05.23 |
[Django]장고 템플릿 태그 주석 다는법 (0) | 2025.05.22 |
[Django] 업로드한 사진을 화면에 표시하는 방법 (2) | 2025.05.22 |
[Django] forms에 체크박스 넣는방법 (7) | 2025.05.20 |