本篇文章为大家展示了使用Django框架如何实现一个分页功能,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
导入分页模块并修改views
#只需修改index函数即可
from django.core.paginator import Paginator
def index(request):
messages = models.Message.objects.all() #获取全部数据
limit = 10
paginator = Paginator(messages, limit) #按每页10条分页
page = request.GET.get('page','1') #默认跳转到第一页
result = paginator.page(page)
return render(request, 'guestbook/index.html', {'messages' : result})
修改html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>留言板</title>
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="external nofollow" crossorigin="anonymous">
</head>
<body>
<table class="table table-striped table-bordered table-hover table-condensed">
<thead>
<tr class="danger">
<th>留言时间</th>
<th>留言者</th>
<th>标题</th>
<th>内容</th>
</tr>
</thead>
<tbody>
{% if messages %}
{% for message in messages %}
<tr class="{% cycle 'active' 'success' 'warning' 'info' %}">
<td>{{ message.publish|date:'Y-m-d H:i:s' }}</td>
<td>{{ message.username }}</td>
<td>{{ message.title }}</td>
<td>{{ message.content }}</td>
</tr>
{% endfor %}
{% else %}
<tr>
<td colspan="4">无数据</td>
</tr>
{% endif %}
</tbody>
</table>
<!-- 分页开始 -->
<div>
<ul class="pagination">
<li><a href="/guestbook/index/?page=1" rel="external nofollow" >首页</a></li>
{% if messages.has_previous %}
<li><a href="/guestbook/index/?page={{ messages.previous_page_number }}" rel="external nofollow" >上一页</a></li>
{% endif %}
{% for num in messages.paginator.page_range %}
<li><a href="/guestbook/index/?page={{ num }}" rel="external nofollow" >{{ num }}</a></li>
{% endfor %}
{% if messages.has_next %}
<li><a href="/guestbook/index/?page={{ messages.next_page_number }}" rel="external nofollow" >下一页</a></li>
{% endif %}
<li><a href="/guestbook/index/?page={{ messages.paginator.num_pages }}" rel="external nofollow" >尾页</a></li>
</ul>
</div>
<!-- 分页结束 -->
<div>
<a class="btn btn-xs btn-primary" href="/guestbook/create/" rel="external nofollow" >去留言</a>
</div>
</body>
</html>
上述内容就是使用Django框架如何实现一个分页功能,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注天达云行业资讯频道。