Pagination CBV (class based views)

이다연·2021년 4월 2일
0

Django

목록 보기
28/33

corey schafer - part 11

Paginator object

Methods and Attribute

1. views

we don't need to import Paginator class. Set an attribute ' paginate_by' on our listview

class HomeView(ListView):
    model = Post
    template_name = 'home.html'
    ordering = ['-post_date']
    paginate_by = 2

for now, we cannot see the articles in the next page
we can specify the url 'http://127.0.0.1:8000/?page=2'

2. templates

Class based view already passes in context we need.

  1. if paginated

  2. if has_previous
    2-1. link to very first page href="?page=1
    2-2. link to previous page href="?page={{ page_obj.previous_page_number }}

  3. for page range
    3-1. if current page(page_obj.number == num) is equal to page_obj.paginator.page_range for loop
    3-2. show up and down 3 page numbers from current page
    uses pipe |add:'-3'

  4. if has_next
    page_obj.paginator.num_pages: number of total pages

Code

      <div class="col-6">
      {% if is_paginated %}
<!-- Previous -->
          {% if page_obj.has_previous %}
             <a class="btn btn-outline-info mb-4" href="?page=1">First</a>
             <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a>
          {% endif%}
<!-- List -->
          {% for num in page_obj.paginator.page_range %}
            {% if page_obj.number == num %}
              <a class="btn btn-outline-info mb-4" href="?page={{ num }}">{{ num }}</a>
            {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
              <a class="btn btn-outline-info mb-4" href="?page={{ num }}">{{ num }}</a>
            {% endif %}
          {% endfor %}
<!--   Next       -->
          {% if page_obj.has_next %}
             <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.next_page_number}}">Next</a>
             <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.paginator.num_pages }}">Last</a>
          {% endif%}

      {% endif %}


      </div>

profile
Dayeon Lee | Django & Python Web Developer

0개의 댓글