1. 장고 뷰에서 데이터 베이스 paginator로 설정 

cd demo

vi views.py

# -*- coding: utf-8 -*-

from __future__ import unicode_literals


from django.shortcuts import render

from django.views import View

from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger


from .models import *


# Create your views here.

class catetc_base(View):

  def get(self, request, *args, **kwargs):

    products = Product.objects.all()

    # 한 페이지에 보여줄 아이템 개수

    page_item_num = 5

    paginator = Paginator(products, page_item_num)

    page = request.GET.get('page')

    items = None

    try:

      items = paginator.page(page)

    except PageNotAnInteger:

      items = paginator.page(1)

    except EmptyPage:

      items = paginator.page(paginator.num_pages)


    return render(request, 'demo/demo_base.html', context={'items':items})


2. html 에서 페이지 표시 구현

vi templates/demo/demo_base.html

<!doctype html>

<html lang="ko">

<html>

  <head>

    <meta charset="utf-8">

    <title>Paginator Demo</title>

  </head>


  <body>

    <a>Products</a> <br>

    <table>

      <thead>

        <tr>

          <th> pid    </th>

          <th> cat1id </th>

          <th> cat2id </th>

          <th> cat3id </th>

          <th> pname  </th>

          </tr>

      </thead>

      <tbody>

        {% for w in items %}

        <tr>

          <td> {{ w.pid }}    </td>

          <td> {{ w.cat1id }} </td>

          <td> {{ w.cat2id }} </td>

          <td> {{ w.cat3id }} </td>

          <td> {{ w.pname }}  </td>

        </tr>

        {% endfor %}

      </tbody>

    </table>


    <div class="pagination">

    <span class="step-links">

      {% if items.has_previous %}

        <a href="?page={{ items.previous_page_number }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}">previous</a>

      {% endif %}

      <span class="current">

        Page {{ items.number }} of {{ items.paginator.num_pages }}.

      </span>

      {% if items.has_next %}

        <a href="?page={{ items.next_page_number }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}"> next </a> &nbsp

      {% endif %}

    </span>

    </div>

  </body>

</html>


+ Recent posts