首页 > 代码库 > django分页实现

django分页实现

from django.shortcuts import render,render_to_response
from app1 import models
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger

# Create your views here.
def schools(request):
obj=models.School.objects.all()
objCount=obj.count()
paginator = Paginator(obj, 24) # Show 25 contacts per page
page = request.GET.get(‘page‘)
try:
contacts = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
contacts = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
contacts = paginator.page(paginator.num_pages)

return render_to_response(‘schools.html‘, {"schools": contacts})

模板部分-------------------------

<table border="2px">
<caption>学校表格</caption>
<thead>
<tr>
<th>name</th>
<th>city</th>
<th>addr</th>
</tr>
</thead>
<tbody>

{% for contact in schools %}
{# Each "contact" is a Contact model object. #}
{# {{ contact.full_name|upper }}<br />#}
<tr>
<td>{{ contact.name }}</td>
<td>{{ contact.city }}</td>
<td>{{ contact.addr }}</td>

</tr>
{% endfor %}
</tbody>
</table>

<div class="pagination">
<span class="step-links">
{% if schools.has_previous %}
<a href="http://www.mamicode.com/?page={{ schools.previous_page_number }}">上一页</a>
{% endif %}

<span class="current">
第 {{ schools.number }} 页||共 {{ schools.paginator.num_pages }}页
</span>

{% if schools.has_next %}
<a href="http://www.mamicode.com/?page={{ schools.next_page_number }}">下一页</a>
{% endif %}
</span>
</div>

</body>





django分页实现