我想使用django.core.paginator,我对render_to_response函数有疑问。 views.py中名为 pages 的变量应该返回页数等但不是。 我看到的所有故事,但分页不起作用。 views.py 文件如下所示:
from django.shortcuts import render_to_response, get_object_or_404
from django.db.models import Q
from cms.models import Story, Category
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
def listing(request):
story_list = Story.objects.all()
p = Paginator(story_list, 2) # Show 2 contacts per page
page = request.GET.get('page')
try:
pages = p.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
pages = p.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
pages = p.page(p.num_pages)
return render_to_response('/usr/local/lib/python2.7/dist-packages/django/bin/project_003/cms/templates/cms/story_list.html', {"pages": pages})
story_list.html 就像这样:
{% extends "/usr/local/lib/python2.7/dist-packages/django/bin/project_003/cms/templates/cms/base.html" %}
{% block content %}
{% if heading %}
<h1>{{ heading }}</h1>
{% endif %}
<ul id="story-list">
{% for story in story_list %}
<li><a href="{{story.get_absolute_url}}">{{story.title}}</a></li><br>
{{pages.p.num_pages}}
{% endfor %}
<div class="pagination">
<span class="step-links">
{% if pages.has_previous %}
<a href="?page={{ pages.previous_page_number }}">previous</a>
{% endif %}
<span class="current">
Page {{ pages.number }} of {{ pages.paginator.num_pages }}.
</span>
{% if pages.has_next %}
<a href="?page={{ pages.next_page_number }}">next</a>
{% endif %}
</span>
</div>
</ul>
{% endblock %}
哪里出错了?
答案 0 :(得分:1)
直接从文档中更改变量名称:https://docs.djangoproject.com/en/dev/topics/pagination/#using-paginator-in-a-view
观点:
def listing(request):
story_list = Story.objects.all()
p = Paginator(story_list, 2) # Show 2 contacts per page
page = request.GET.get('page')
try:
stories = p.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
stories = p.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
stories = p.page(p.num_pages)
return render_to_response('/usr/local/lib/python2.7/dist-packages/django/bin/project_003/cms/templates/cms/story_list.html', {"stories": stories})
模板:
<ul id="story-list">
{% for story in stories %}
<li><a href="{{story.get_absolute_url}}">{{story.title}}</a></li><br>
{% endfor %}
</ul>
<div class="pagination">
<span class="step-links">
{% if stories.has_previous %}
<a href="?page={{ stories.previous_page_number }}">previous</a>
{% endif %}
<span class="current">
Page {{ stories.number }} of {{ stories.paginator.num_pages }}.
</span>
{% if stories.has_next %}
<a href="?page={{ stories.next_page_number }}">next</a>
{% endif %}
</span>
</div>