Flask实战第60天:帖子分页技术实现

编辑manage.py,添加测试帖子

@manager.command
def create_test_post():
    for x in range(1, 100):
        title = '标题{}'.format(x)
        content = '内容:{}'.format(x)
        board = BoardModel.query.first()
        author = FrontUser.query.first()
        post = PostModel(title=title, content=content)
        post.board = board
        post.author = author
        db.session.add(post)
        db.session.commit()
    print('测试帖子添加成功')

运行

python manage.py create_test_post

在 flask框架中,我们可以使用Flask Paginate插件来实现分页

https://pythonhosted.org/Flask-paginate/

安装插件

pip install flask-paginate

编辑配config.py,配置每页显示的帖子数

#flask-paginate的相关配置
PER_PAGE = 6   #每页显示6篇帖子

编辑首页的视图函数,编辑front.views.py

...
from flask_paginate import Pagination, get_page_parameter


#get_page_parameter可以获取到当前页

现在刷新首页只会显示6篇帖子了

实现翻页

编辑front_index.html,在帖子下面加上

刷新页面,发现没有样式

解决这个问题,需要在实例化Pagination加上指定 bootstrap版本的参数即可

让它居中显示,只需要在外面加个div,设置个样式即可

<div style="text-align: center">
    {{ pagination.links }}
</div>

原文地址:https://www.cnblogs.com/sellsa/p/9750307.html