欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > Django分页

Django分页

2024/10/24 7:35:44 来源:https://blog.csdn.net/wanghuizheng/article/details/139499049  浏览:    关键词:Django分页

1、在视图函数文件中引入‘分页器’

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

2、给原来的罗列信息函数,添加分页功能,即按照页码,只返回部分信息。

@login_required
def article_list(request):articles_list = ArticlePost.objects.filter(author=request.user)#根据查询的articles_list创建分页对象,每页3个paginator = Paginator(articles_list, 3)#获得GET请求的参数:page的值,也就是页码数page = request.GET.get('page')try:current_page = paginator.page(page)#按照页码,使用分页器的page方法得到页面内容articles = current_page.object_list#得到页面内容的对象列表except PageNotAnInteger:#如果请求的页码不是整数current_page = paginator.page(1)#返回第一页articles = current_page.object_listexcept EmptyPage:#如果页码值为空,或URL参数中没有pagecurrent_page = paginator.page(paginator.num_pages)#返回最后一页articles = current_page.object_listcontext = {'articles': articles, 'page':current_page}return render(request, 'article/column/article_list.html', context)

3、向项目的根templates中添加paginator.html模板,用于在需要分页的地方include

注意在写href时,问号和page之间没有空格

<div class="pagination"><span class="step-links">{% if page.has_previous %}   <!--判断是否有上一页--><a href="?page={{ page.previous_page_number }}">Previous</a>{% endif %}<span class="current">Page {{ page.number }} of {{ page.paginator.num_pages }}</span>{% if page.has_next %}    <!--判断是否有下一页--><a href="?page={{ page.next_page_number}}">Next</a>{% endif %}</span>
</div>

4、在原来的罗列信息页面中,引入分页模板

<table>
...
</table>{% include "paginator.html" %}

5、运行结果如下

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com