Django 로 게시판 만들기(20). 게시판 Pagination

.·2020년 7월 28일
0

게시판만들기

목록 보기
20/21

1. 부트스트랩 : pagination 관련 html 퍼오기

게시판에 글이 쌓이면 쌓일 수록 글 목록이 아래로 내려가면서 늘어날 것이다. 처음 너댓개 정도는 그런대로 봐줄만 하겠지만 극단적으로 100개 면 봐주기가 곤란할 것이다.

그래서 page 를 나눠주는 pagination 을 할건데,
board_list.html 에 글 목록과 글쓰기 버튼이 있는 코드 사이에다가 아래와 같은 포맷을 넣고

<div class="row mt-2">
  <div class="col-12">
    """" 여기에 부트스트랩 페이지네이션 코드 복붙 """
    <nav aria-label="Page navigation example">
     <ul class="pagination justify-content-center">
      <li class="page-item"><a class="page-link" href="#">Previous</a></li>
      <li class="page-item"><a class="page-link" href="#">1</a></li>
      <li class="page-item"><a class="page-link" href="#">2</a></li>
      <li class="page-item"><a class="page-link" href="#">3</a></li>
      <li class="page-item"><a class="page-link" href="#">Next</a></li>
    </ul>
   </nav>
  </div>
</div>

태그 ul 속성에 justify-content-center 를 적용하면 가운데로 정렬이 된다.
입맛에 맞게 알아서 조정한다.

2. board/views.py 에 Paginator 불러오기

from django.core.paginator import Paginator

board_list() 함수 안에 위에 import 한 페이지네이터 코드를 작성해 보자.

def board_list(request):
    all_boards  = Board.objects.all().order_by('-id')
    # 변수명을 all_boards 로 바꿔주었다.
    page        = int(request.GET.get('p', 1))
    # p라는 값으로 받을거고, 없으면 첫번째 페이지로
    pagenator   = Paginator(all_boards, 2)
    # Paginator 함수를 적용하는데, 첫번째 인자는 위에 변수인 전체 오브젝트, 2번째 인자는
    # 한 페이지당 오브젝트 2개씩 나오게 설정
    boards      = pagenator.get_page(page)
    # 처음 2개가 세팅 된다.
    return render(request, 'board_list.html', {"boards":boards})

request.GET은 GET으로 받는 인자들을 다 포함하는 딕셔너리 객체이다.

get() 메서드는 키값이 딕셔너리 안에 있으면 밸류값을 리턴해준다. 키값이 존재하지 않으면 디폴트값 None을 리턴한다.

request.GET.get()은 위 두 개념을 합친 것으로 GET요청이 접근할 수 있는 키와 밸류값을 이용한다. 이것은 장고 뷰스에서 대부분 쓰여진다.

3. board_list.html 수정하기

'이전으로' 와 '다음으로' 의 a 태그 href 속성을 수정하고 페이지 1에 href 속성도 수정했는데 에러창이 나온다.

page1 에서는 이전 페이지가 없기 때문에 위와 같은 에러 페이지를 만날 수 있다.
html 파일에 if 를 사용해서 이전 페이지가 있으면 코드를 그대로 사용하고, 이전 페이지가 없는 상황이 발생할 때 href 속성을 초기화하고 a 태그를 비활성화 하도록 바꾸자.

{% extends "base.html" %} {% block content %}
<div class="row mt-5">
  <div class="col-12">
    <table class="table">
      <thead class="thead-dark">
        <tr>
          <th scope="col">#</th>
          <th scope="col">제목</th>
          <th scope="col">아이디</th>
          <th scope="col">작성일</th>
          <th scope="col">최종수정일</th>
        </tr>
      </thead>

      <tbody>
        {% for board in boards %}
        <tr>
          <th scope="row">{{ board.id }}</th>
          <td>{{ board.title }}</td>
          <td>{{ board.writer }}</td>
          <td>{{ board.created_at }}</td>
          <td>{{ board.updated_at }}</td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
  </div>
</div>
<div class="row mt-2">
  <div class="col-12">
    <nav aria-label="Page navigation example">
      <ul class="pagination justify-content-center">
        {% if boards.has_previous %}
        <li class="page-item">
          <a class="page-link" href="?p={{ boards.previous_page_number }}"
            >Previous</a
          >
        </li>
        {% else %}
        <li class="page-item disabled">
          <a class="page-link" href="#">Previous</a>
        </li>
        {% endif %}
        <li class="page-item">
          <a class="page-link" href="#"
            >{{ boards.number }} / {{ boards.paginator.num_pages }}</a
          >
        </li>
        {% if boards.has_next %}
        <li class="page-item">
          <a class="page-link" href="?p={{ boards.next_page_number }}">Next</a>
        </li>
        {% else %}
        <li class="page-item disabled">
          <a class="page-link" href="#">Next</a>
        </li>
        {% endif %}
      </ul>
    </nav>
  </div>
</div>
<div class="row mt-2">
  <div class="col-12">
    <button class="btn btn-primary">글쓰기</button>
  </div>
</div>
{% endblock %}

profile
.

0개의 댓글