牌語備忘録 -pygo

あくまでもメモです。なるべくオフィシャルの情報を参照してください。

牌語備忘録 -pygo

Djnago のページネーションのメモ

(Python2.7, Djnago1.4)

Djnagoチュートリアルその4で出来上がったアプリに追加する形で。

templates/polls/list.html

{% for poll in polls %}
    {# Each "poll" is a poll model object. #}
    {{ poll.question|upper }}<br />
{% endfor %}

<div class="pagination">
    <span class="step-links">
        {% if polls.has_previous %}
            <a href="?page={{ polls.previous_page_number }}">previous</a>
        {% endif %}

        <span class="current">
            Page {{ polls.number }} of {{ polls.paginator.num_pages }}
        </span>

        {% if polls.has_next %}
            <a href="?page={{ polls.next_page_number }}">next</a>
        {% endif %}
    </span>
</div>

polls/urls.py

 urlpatterns = patterns('',
                        url(r'^$',
                            ListView.as_view(
                               #queryset=Poll.objects.order_by('-pub_date')[:5],
                               queryset=Poll.objects.order_by('-pub_date'),
                                context_object_name='latest_poll_list',
                                template_name='polls/index.html')),

:
                        url(r'^(?P<poll_id>\d+)/vote/$', 'polls.views.vote'),
                       url(r'^listting/$', 'polls.views.listing'), # add
 )

polls/views.py

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

:

def listing(request):
    poll_list = Poll.objects.all()
    paginator = Paginator(poll_list, 25) # Show 25 polls per page

    page = request.GET.get('page')
    try:
        polls = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        polls = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        polls = paginator.page(paginator.num_pages)

    return render_to_response('polls/list.html', {"polls": polls})

確認用データ投入

$ python manage.py shell
>>> [Poll(question="question%d" % i, pub_date=timezone.now()).save() for i in range(50)]
>>> Poll.objects.all()

Webブラウザで確認

$ python manage.py runserver