0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[python] Django Paginatorを用いたページ選択画面

Last updated at Posted at 2022-12-21

Code

views.py
from .models import Venue
from django.core.paginator import Paginator

def list_venues(request):

    p = Paginator(Venue.objects.all().order_by('name'), 2)
    # 表示するオブジェクトの個数を指定する ここでは2個分を指定

    page = request.GET.get('page')
    # urlからページの情報を読み取る

    venues = p.get_page(page)
    # ページの情報に相応するデータ

    nums = "a" * venues.paginator.num_pages
    # 総ページ数をaの数で渡す(htmlでint型でrootができないため)

    return render(request, 'list_venues.html',
                  {
                      "venues": venues,
                      "nums": nums
                  })
list_venues.html
{% for venue in venues %}
     {{venue}}
{% endfor %}
<!--指定した数だけ表示される-->

{{venues}}  <!--<Page 1 of 2>-->
{{venues.has_previous}}  <!--False -->
{{venues.has_next}}  <!--True -->
{{venues.number}}  <!--1-->
{{venues.paginator.num_pages}}  <!--2-->

Bootstrap(4.x)を用いたページ選択ボタン

list_venues.html
{% if venues.has_previous %}

<li class="page-item"><a href="?page=1" class="page-link">&laquo First</a></li>
<li class="page-item"><a href="?page={{venues.previous_page_number}}" class="page-link">previous</a></li>

{% else %}

<li class="page-item disabled"><a class="page-link">&laquo First</a></li>
<li class="page-item disabled"><a class="page-link">previous</a></li>

{% endif %}


{% for i in nums %}

<li class="page-item"><a class="page-link " href="?page={{forloop.counter}}">{{forloop.counter}}
    </a></li>

{% endfor %}

{% if venues.has_next %}
<li class="page-item"><a href="?page={{venues.next_page_number}}" class="page-link">next</a></li>
<li class="page-item"><a href="?page={{venues.paginator.num_pages}}" class="page-link">Last &raquo </a></li>


{% else %}

<li class="page-item disabled"><a class="page-link">next</a></li>
<li class="page-item disabled"><a class="page-link">Last &raquo </a></li>

{% endif %}

ページ1

image.png

ページ2

image.png

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?