Welcome folks today in this blog post we will be paginating users
in flask using flask-paginate
library using bootstrap
framework in browser. All the full source code of the application is shown below.
Get Started
In order to get started you need to install the below library using the pip
command as shown below
pip install flask-paginate
After that you need to create the app.py
file and copy paste the following code
app.py
1 2 3 4 5 6 7 8 9 10 |
from flask import Flask, render_template from flask_paginate import Pagination, get_page_args app = Flask(__name__) app.template_folder = '' users = list(range(100)) if __name__ == '__main__': app.run(debug=True) |
As you can see we are importing the flask
library and then we are importing the flask pagination
module and then we are using the list
method to generate 100 test
users using the range()
method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
@app.route('/') def index(): page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='per_page') total = len(users) pagination_users = get_users(offset=offset, per_page=per_page) pagination = Pagination(page=page, per_page=per_page, total=total, css_framework='bootstrap4') return render_template('index.html', users=pagination_users, page=page, per_page=per_page, pagination=pagination, ) |
As you can see we have assigned a route
whenever user goes to the /
homepage then we will be showing the index.html
template using the render_template()
method and inside it we are passing the users
array and inside it we are also passing the total pages
and users per page value.
And now we need to make the index.html
file and copy paste the below html
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>flask-bootstrap example</title> <!-- Bootstrap --> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css"> </head> <body> <div class="container"> {{ pagination.links }} <div class="table-responsive"> <table class="table table-hover"> <thead> <tr> <th>#</th> <th>Value</th> </tr> </thead> <tbody> {% for user in users %} <tr> <td>{{ loop.index + (page - 1) * per_page }}</td> <td>{{ user }}</td> </tr> {% endfor %} </tbody> </table> </div> {{ pagination.links }} </div> </body> </html> |
As you can see we are displaying the data
inside the table and also we have the pagination
links displayed based upon the total users
present inside the array.