03_Web

[Django]Paginator를 활용한 페이징(paging)

chuuvelop 2025. 5. 22. 17:37
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 }}">&#10094; 이전</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 }}">다음 &#10095;</a>
        {% endif %}
    {% endif %}
    <!-- 페이징 end-->


</body>
</html>
728x90