ListView Django -next分页中的prev链接丢失

时间:2014-03-13 05:50:15

标签: python django pagination django-class-based-views

我使用django与ListView进行分页。 一切都按预期工作。但模板上没有下一个和上一个链接。

我在这里错过了什么吗?

这是urls.py

from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.views.generic.list import ListView
from demoapp.models import Candidate
admin.autodiscover()

urlpatterns = patterns('',

    url(r'^admin/', include(admin.site.urls)),
    url(r'^test/', ListView.as_view(
                    model=Candidate,
                    paginate_by='10',
                    queryset=Candidate.objects.all(),
                    context_object_name="tasks",                
                    template_name='index.html')),
)

models.py

from django.db import models
class Candidate(models.Model):
    name=models.CharField(max_length=255)

这是index.html

<ol>
{% for t in tasks %}
<li><p>{{t.name}}</p></li>
{% endfor %}
</ol>
<div class="pagination">
      <ul>
          {% if paginator.has_previous %}
              <li><a href="?page={{ paginator.previous_page_number }}">Previous</a></li>
          {% endif %}
          {% for pg in paginator.page_range %}
              {% if posts.number == pg %}
                  <li class="active"><a href="?page={{ pg }}">{{ pg }}</a></li>
              {% else %}
                  <li><a href="?page={{ pg }}">{{ pg }}</a></li>
              {% endif %}
          {% endfor %}
          {% if paginator.has_next %}
              <li><a href="?page={{ paginator.next_page_number }}">Next</a></li>
          {% endif %}
      </ul>
    </div>

1 个答案:

答案 0 :(得分:2)

因为Django在视图模板中不知道paginator是什么,所以没有显示任何内容。

查看the example in the documentation,您似乎需要将视图中的paginator替换为tasks -

<div class="pagination">
  <ul>
      {% if tasks.has_previous %}
          <li><a href="?page={{ tasks.previous_page_number }}">Previous</a></li>
      {% endif %}
      {% for pg in tasks.page_range %}
          {% if posts.number == pg %}
              <li class="active"><a href="?page={{ pg }}">{{ pg }}</a></li>
          {% else %}
              <li><a href="?page={{ pg }}">{{ pg }}</a></li>
          {% endif %}
      {% endfor %}
      {% if tasks.has_next %}
          <li><a href="?page={{ tasks.next_page_number }}">Next</a></li>
      {% endif %}
  </ul>
</div>