ページネーション機能の追加 [Django]

ページネーション機能の追加 [Django]


donald chi / 2017-09-21 23:44

音声ファイル作成中...
Audio: Visited: 2540


条件

MyBlogというモデルから定義されたテーブルにブログ文章データがあるとします。

@python_2_unicode_compatible
class MyBlog(models.Model):
    title = models.CharField(max_length=255)
    body = MarkdownxField()
    author = models.ForeignKey(User, null=True)
    publishing_date = models.DateTimeField(auto_now_add=True)
    slug = models.SlugField()

    def __str__(self):
        return self.title

目的

今回は、Django Pure Pagination パッケージを使って1ページに6文章ずつ表示する、簡単なページネーション機能を実装します。


具体的なやり方

1. Pure Paginationパッケージのインストール

pip install django-pure-pagination

2. setting.pyの設定

2.1 INSTALLED_APPSにpure_paginationを追加
INSTALLED_APPS = (
        ...
    'pure_pagination',
)
2.2 pagination設定を作成
PAGINATION_SETTINGS = {
    'PAGE_RANGE_DISPLAYED': 2,
    'MARGIN_PAGES_DISPLAYED': 2,
    'SHOW_FIRST_PAGE_WHEN_INVALID': True,
}

各設定行は図の様な意味があります。 pagination.gif

今回は、最初、最後、真ん中共に2ページずつ表示し、ページ数が無効な場合、最初のページを表示する様に設定します。

3. urls.pyの設定

BlogListViewのurlを設定します。

urls.py

urlpatterns = [
    url(r'^$', BlogListView.as_view(), name='blog_list'),
]

4. views.pyに置けるBlogListViewクラスの定義

from django.core.paginator import Paginator
from django.core.paginator import EmptyPage, InvalidPage
from django.core.paginator import PageNotAnInteger
from pure_pagination.mixins import PaginationMixin

class BlogListView(PaginationMixin, ListView):
    model = MyBlog
    template_name = "blog_list.html"
    paginate_by = 6 #6文章ごとにページ分割する

    def get_context_data(self, **kwargs):
        blog_list = MyBlog.objects.all().order_by('-publishing_date')
        #set page
        paginator = Paginator(blog_list, 6)  #6文章ごとにページ分割する

    #pageパラメータを取得して、表示するページを指定
    #pageパラメータが無効な場合、1ページ目を指定
        try:
            page = int(self.request.GET.get('page'))
        except:
            page = 1

    #上で設定したページに該当する文章を取得
        try:
            blog_list = paginator.page(page)
        except(EmptyPage, InvalidPage):
            blog_list = paginator.page(1)

        context['object_list'] = blog_list
        return context

    def get_queryset(self):
        return MyBlog.objects.order_by('publishing_date')

5. templateページを定義

今回はBlogListViewの定義でblog_list.htmlをtemplateとして指定したので、blog_list.htmlを作成

blog_list.html
{# ページネーション部分 #}
{% if is_paginated %}
    <ul class="pagination">
        {% if page_obj.has_previous %}
            <li><a 
                href="?{{ page_obj.previous_page_number.querystring }}"
                    >previous</a>
            </li>

        {% endif %}
        {% for link_page in page_obj.pages %}
            {% if link_page %}
                {% if link_page == page_obj.number %}
                    <li class="active"><a href="">{{ link_page }}</a></li>
                {% else %}
                    <li><a 
                                href="?{{ link_page.querystring  }}"
                            >{{ link_page }}</a>
                    </li>
                {% endif %}
            {% else %}
                {# 省略された部分の表示内容 #}
                <li class="disabled"><a href="#">...</a></li>
            {% endif %}
        {% endfor %}

        {% if page_obj.has_next %}
            <li><a 
                        href="?{{ page_obj.next_page_number.querystring }}"
                    >next</a>
            </li>
        {% endif %}
    </ul>
{% endif %}

結果

result.gif


参考文献

  1. django-pure-pagination repo

0

0

Share with: Facebook Twitter Google+ LinkedIn Wechat Email Print
Tags: django

Comments: 16 件


Dianne Bennett
nwfdjffl@nsijqgg.com

I discovered your ページネーション機能の追加 [Django] page and noticed you could have a lot more traffic. I have found that the key to running a website is making sure the visitors you are getting are interested in your subject matter. We can send you targeted traffic and we let you try it for free. Get over 1,000 targeted visitors per day to your website. Start your free trial: http://insl.co/11 Unsubscribe here: http://stpicks.com/2ruse

Nell Renteria
nell.renteria@gmail.com

For a limited time we have lowered the rate on targeted website traffic. We have visitors from virtually every country on Earth. Each visitor is targeted by both country and keywords that you submit when you start your free trial period. If you need more visitors or product sales try our service free for seven days and we will send you 500 free visitors during the trial. There are no contracts and if you cancel during the trial period you will not be charged anything! Start your trial today: http://stpicks.com/2rusd Unsubscribe here: http://stpicks.com/2ruse

Dianne Bennett
jtctolmr@ovfdsbpxzm.com

I came across your ページネーション機能の追加 [Django] website and wanted to let you know that we have decided to open our POWERFUL and PRIVATE website traffic system to the public for a limited time! You can sign up for our targeted traffic network with a free trial as we make this offer available again. If you need targeted traffic that is interested in your subject matter or products start your free trial today: http://s.miku.moe/jbpuz Unsubscribe here: https://twe.lv/gg

Nicole Mawrey
dqiebxmopk@gzznggql.com

I came to your ページネーション機能の追加 [Django] page and noticed you could have a lot more traffic. I have found that the key to running a website is making sure the visitors you are getting are interested in your subject matter. We can send you targeted traffic and we let you try it for free. Get over 1,000 targeted visitors per day to your website. Start your free trial: http://www.1lnk.net//1ol7 Unsubscribe here: https://twe.lv/gg

Nicole Mawrey
svuhvbkprd@mjojdsvktg.com

This is a comment to the ページネーション機能の追加 [Django] webmaster. Your website is missing out on at least 300 visitors per day. Our traffic system will dramatically increase your traffic to your website: http://www.1lnk.net//1ol7 - We offer 500 free targeted visitors during our free trial period and we offer up to 30,000 targeted visitors per month. Hope this helps :) Unsubscribe here: https://twe.lv/gg

Nicole Mawrey
tpcbbwwsxyb@wcihjltgtc.com

I came across your ページネーション機能の追加 [Django] website and wanted to let you know that we have decided to open our POWERFUL and PRIVATE web traffic system to the public for a limited time! You can sign up for our targeted traffic network with a free trial as we make this offer available again. If you need targeted traffic that is interested in your subject matter or products start your free trial today: http://www.1lnk.net//1ol7 Unsubscribe here: https://twe.lv/gg

Heidi Wright
mysmxl@klnptefc.com

I came to your ページネーション機能の追加 [Django] page and noticed you could have a lot more traffic. I have found that the key to running a website is making sure the visitors you are getting are interested in your subject matter. We can send you targeted traffic and we let you try it for free. Get over 1,000 targeted visitors per day to your website. Start your free trial: http://www.1lnk.net//1ol7 Unsubscribe here: https://twe.lv/gg

Lillian Davis
ezorvkt@faaxdxgmlmc.com

I came to your ページネーション機能の追加 [Django] page and noticed you could have a lot more traffic. I have found that the key to running a website is making sure the visitors you are getting are interested in your subject matter. We can send you targeted traffic and we let you try it for free. Get over 1,000 targeted visitors per day to your website. Start your free trial: http://2url.de/gbr Unsubscribe here: https://twe.lv/gg

Alice Lowe
kppwivek@qmurextpwu.com

I came to your ページネーション機能の追加 [Django] page and noticed you could have a lot more traffic. I have found that the key to running a website is making sure the visitors you are getting are interested in your subject matter. We can send you targeted traffic and we let you try it for free. Get over 1,000 targeted visitors per day to your website. Start your free trial: http://ralive.de/201z Unsubscribe here: http://2url.de/1alt

Alice Lowe
rahyydkkp@rnxapbcvo.com

This is a comment to the ページネーション機能の追加 [Django] webmaster. Your website is missing out on at least 300 visitors per day. Our traffic system will dramatically increase your traffic to your website: http://ralive.de/201z - We offer 500 free targeted visitors during our free trial period and we offer up to 30,000 targeted visitors per month. Hope this helps :) Unsubscribe here: http://2url.de/1alt

Kelley Brown
jbfejxkfxd@faxfxm.com

This is a comment to the ページネーション機能の追加 [Django] webmaster. Your website is missing out on at least 300 visitors per day. Our traffic system will dramatically increase your traffic to your website: http://y.rxhnet.de/2w6y - We offer 500 free targeted visitors during our free trial period and we offer up to 30,000 targeted visitors per month. Hope this helps :) Unsubscribe here: http://sp7.site/8

Kelley Brown
rkeeedgjbb@vnknif.com

I discovered your ページネーション機能の追加 [Django] page and noticed you could have a lot more traffic. I have found that the key to running a website is making sure the visitors you are getting are interested in your subject matter. We can send you targeted traffic and we let you try it for free. Get over 1,000 targeted visitors per day to your website. Check it out here: http://y.rxhnet.de/2w6y Unsubscribe here: http://sp7.site/8

Kelley Brown
gzzfhprvggs@jyebvzgvtg.com

This is a message to the ページネーション機能の追加 [Django] webmaster. Your website is missing out on at least 300 visitors per day. Our traffic system will dramatically increase your traffic to your site: http://sp7.site/7 - We offer 500 free targeted visitors during our free trial period and we offer up to 30,000 targeted visitors per month. Hope this helps :) Unsubscribe here: http://sp7.site/8

Kelley Brown
awcxve@cymkwlotzy.com

I came across your ページネーション機能の追加 [Django] website and wanted to let you know that we have decided to open our POWERFUL and PRIVATE website traffic system to the public for a limited time! You can sign up for our targeted traffic network with a free trial as we make this offer available again. If you need targeted traffic that is interested in your subject matter or products start your free trial today: http://y.rxhnet.de/2w6y Unsubscribe here: http://sp7.site/8

Kelley Brown
viqufig@ljcmali.com

I came across your ページネーション機能の追加 [Django] website and wanted to let you know that we have decided to open our POWERFUL and PRIVATE website traffic system to the public for a limited time! You can sign up for our targeted traffic network with a free trial as we make this offer available again. If you need targeted traffic that is interested in your subject matter or products start your free trial today: http://sp7.site/7 Unsubscribe here: http://sp7.site/8

Kelley Brown
vqgimi@vpemmrfvuqo.com

I came to your ページネーション機能の追加 [Django] page and noticed you could have a lot more traffic. I have found that the key to running a website is making sure the visitors you are getting are interested in your subject matter. We can send you targeted traffic and we let you try it for free. Get over 1,000 targeted visitors per day to your website. Check it out here: http://likes.avanimisra.com/4p4l Unsubscribe here: http://sp7.site/8 [url=http://likes.avanimisra.com/4p4l]Kelley Brown[/url]

Add Comment

Name:
Email:
Comment: