I'm trying to display 5 record per page. However, I not sure how to configure the li class. For instance, click the 2 and it will redirect to next 5 record on second page and click previous it will redirect from 2 to 1 to first page.
manageSmartphone.html
<div >
<div >Showing <b>5</b> out of <b>{{ total }}</b> entries</div>
<ul >
<li ><a href="#">Previous</a></li>
<li ><a href="#" id="page" name="page">1</a></li>
<li ><a href="#" id="page" name="page">2</a></li>
<li ><a href="#" id="page" name="page">3</a></li>
<li ><a href="#" id="page" name="page">4</a></li>
<li ><a href="#" id="page" name="page">5</a></li>
<li ><a href="#" id="page" name="page">Next</a></li>
</ul>
</div>
app.py
@app.route('/manageSmartphone', methods = ['GET','POST'])
def manageSmartphone():
conn = get_db_connection()
page = request.args.get('page', type=int, default=1)
limit= 5
offset = page*limit - limit
smartphones = conn.execute('SELECT * FROM Smartphone').fetchall()
total = len(smartphones)
smartphones = conn.execute("SELECT * FROM Smartphone LIMIT ? OFFSET ?", (limit, offset)).fetchall()
return render_template('manageSmartphone.html', smartphones = smartphones , total = total)
CodePudding user response:
Implementing pagination can be challenging for several reasons,
I would suggest you using the paginate()
method of the Flask-SQLAlchemy
lib
This method takes a page
parameter and a per_page
parameter that you can use to specify the current page and the number of records to display per page
Here is an example of how you could use the paginate()
method to implement pagination that displays 5 records per page in Flask:
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_sqlalchemy import Pagination
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
db = SQLAlchemy(app)
# Define a model representing a record in the database
class Record(db.Model):
id = db.Column(db.Integer, primary_key=True)
brand = db.Column(db.String(80), nullable=False)
model = db.Column(db.String(80), nullable=False)
price = db.Column(db.Integer, nullable=False)
@app.route('/')
def index():
# Get the current page from the request parameters
page = request.args.get('page', 1, type=int)
# Use the paginate() method to get the records for the current page
records = Record.query.paginate(page=page, per_page=5)
# Render the records on a template
return render_template('index.html', records=records)