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

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


donald chi / 2017-09-21 23:44

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


条件

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: 27 件


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]

Rebecca Newton
zgiegtzsda@leohies.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://likes.avanimisra.com/4p4l Unsubscribe here: http://y.rxhnet.de/5kfw

Rebecca Newton
eagxere@okbzuobd.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://likes.avanimisra.com/4p4l Unsubscribe here: http://y.rxhnet.de/5kfw

Rebecca Newton
dyjhicdafqm@jqvocas.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://sp7.site/7 Unsubscribe here: http://y.rxhnet.de/5kfw

sky casino promo codes
AlisonHelvey47@vivie.club

Online casinos indeed earned a great area for people who wanted invest their sparetime more electrifying. And perhaps some of the reasons why this recreational activity becomes really in-demand is involving its capacity to offer you with superb casino games, bonuses, and tournaments. Well it holds true that just about all online casino games have their own own as well as strategies since the comes to winning. While other people of them were purely based on luck, it lets you not mean that since it's make use of any tips which might you expand your chances. Continue reading below and learn a few general approaches for your online casino on the net game. In 1994, MicroGaming has transferred video poker to online casinos, which has proven to be a very good step. Electronic poker was most likely the easiest casino game to transfer online, while the players didn't observe any differences between land-based and internet based variations with the game. Today you understand hundreds of video poker variations in online casino houses. There are even progressive video poker games, offering thousands of dollars in jackpot. However with the improvement top casino site, video poker still remains one quite popular entertainments in land-based casinos. Another thing recent boom of traditional poker, casinos have registered a big income from video poker machines. Every day more people these days are relying on the Internet to funds from. Many people are now experiencing the benefits of making money online. Website businesses provide more freedom than a usual job, web business allow an individual work when and where you motivation. If you like cards, you might want to head straight for the table games on offer at your casino online. Blackjack and poker are by the far the most popular games you will discover. Blackjack requires you even worse up help of as close to 21 as possible, while poker relies you beating the other players by creating the strongest poker handheld. However, unlike slots, both of these card games require prior knowledge and know-how. They require strategic thinking, forward planning and a preliminary understanding of guidelines and sequence of have fun with playing. If you want to start off internet gambling on poker or blackjack, try perform a few free games first and study up for a rules before you test your skills for a real income. In 1995, a less fortunate Sin city resident decreased to the social security office to cash from a $400 verify. His wife had just kicked him associated with your the house and life wasn't looking too dazzling. What to do when important things have gone wrongly diagnosed? Well, take the check and head for Treasure Island Casino in Las Vegas. It is told us that this man smelled so bad that nobody decided to be near him, but luckily them don't love door. As a consequence of his unconventional strategy - he didn't follow the main blackjack

sky casino promo codes
AlisonHelvey47@vivie.club

Online casinos indeed earned a great area for people who wanted invest their sparetime more electrifying. And perhaps some of the reasons why this recreational activity becomes really in-demand is involving its capacity to offer you with superb casino games, bonuses, and tournaments. Well it holds true that just about all online casino games have their own own as well as strategies since the comes to winning. While other people of them were purely based on luck, it lets you not mean that since it's make use of any tips which might you expand your chances. Continue reading below and learn a few general approaches for your online casino on the net game. In 1994, MicroGaming has transferred video poker to online casinos, which has proven to be a very good step. Electronic poker was most likely the easiest casino game to transfer online, while the players didn't observe any differences between land-based and internet based variations with the game. Today you understand hundreds of video poker variations in online casino houses. There are even progressive video poker games, offering thousands of dollars in jackpot. However with the improvement top casino site, video poker still remains one quite popular entertainments in land-based casinos. Another thing recent boom of traditional poker, casinos have registered a big income from video poker machines. Every day more people these days are relying on the Internet to funds from. Many people are now experiencing the benefits of making money online. Website businesses provide more freedom than a usual job, web business allow an individual work when and where you motivation. If you like cards, you might want to head straight for the table games on offer at your casino online. Blackjack and poker are by the far the most popular games you will discover. Blackjack requires you even worse up help of as close to 21 as possible, while poker relies you beating the other players by creating the strongest poker handheld. However, unlike slots, both of these card games require prior knowledge and know-how. They require strategic thinking, forward planning and a preliminary understanding of guidelines and sequence of have fun with playing. If you want to start off internet gambling on poker or blackjack, try perform a few free games first and study up for a rules before you test your skills for a real income. In 1995, a less fortunate Sin city resident decreased to the social security office to cash from a $400 verify. His wife had just kicked him associated with your the house and life wasn't looking too dazzling. What to do when important things have gone wrongly diagnosed? Well, take the check and head for Treasure Island Casino in Las Vegas. It is told us that this man smelled so bad that nobody decided to be near him, but luckily them don't love door. As a consequence of his unconventional strategy - he didn't follow the main blackjack

Rebecca Newton
nfsbtx@bpjoakoih.com

This is a message to the ページネーション機能の追加 [Django] admin. Your website is missing out on at least 300 visitors per day. Our traffic system will dramatically increase your traffic to your site: 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://y.rxhnet.de/5kfw

Christine
wpbwnbj@mkeyvac.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://y.rxhnet.de/2w6y Unsubscribe here: http://y.rxhnet.de/5kfw

Christine
njqyymp@hreoqze.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://tgi.link/5ozd Unsubscribe here: http://y.rxhnet.de/5kfw

Christine
emvdvgulgdr@qbsecwjkyxe.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: https://short.dicecraft.de/7qgi4 Unsubscribe here: http://y.rxhnet.de/5kfw

Krista
kristaday638@yahoo.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://mly.li/2if Unsubscribe here: http://y.rxhnet.de/5kfw

온라인카지노
Georgina-Colwell@hollar70.dynamailbox.com

I and also my pals came examining the nice helpful hints on your site and so suddenly developed an awful feeling I never thanked the web site owner for those secrets. Those young boys appeared to be totally thrilled to learn them and have in effect honestly been taking pleasure in those things. Many thanks for getting very accommodating and for pick out some superior guides millions of individuals are really eager to learn about. Our honest regret for not expressing gratitude to you earlier. https://www.cca365.net

Add Comment

Name:
Email:
Comment: