xiholac761
xiholac761

Reputation: 51

Flask pagination help in Python

I'm trying to create a button in my HTML that will go to the next/previous page when the button is clicked. I've tried pagination and peewee but didn't seem to get it to work.

Here is my app:

from flask import Flask,render_template, request, json
from flask_mysqldb import MySQL
app = Flask(__name__)
app.config['MYSQL_HOST'] = 'example'
app.config['MYSQL_USER'] = 'example'
app.config['MYSQL_PASSWORD'] = 'example'
app.config['MYSQL_DB'] = 'fund_raiser'
mysql = MySQL(app)

@app.route('/funds/pages/', defaults={'page':0})
@app.route('/funds/pages/<int:page>')
def fund_pages(page):
    perpage = 5
    first_page = page*perpage
    cur = mysql.connection.cursor()
    cur.execute("select * from fund_table limit "+str(first_page)+", "+str(perpage)+";", mysql.connection.commit())
    data = cur.fetchall()
    return render_template('funds.html', data=data)

Where do I add the href tag in my html page? What is the correct variable to use?

Upvotes: 0

Views: 1040

Answers (1)

Locke Donohoe
Locke Donohoe

Reputation: 492

This is quite easy with the url_for() function.
You can call the name of the function for the route, and pass it a variable.

href="{{ url_for('fund_pages', page=page_num) }}"

Where page_num is the page number.

To get the page number dynamically, you can simple add or subtract 1 from the current page number. For example, you could store page_prev = current_page - 1 and page_next = current_page + 1.

You can these pass those variables to the url_for function as the page parameter.

Example:

# in fund_pages()
prev_page = page - 1
next_page = page + 1
return render_template('template.hmtl', next_page=next_page, prev_page=prev_page)

# in the template
<a href="{{ url_for('fund_pages', page=prev_page) }}">Previous</a>
<a href="{{ url_for('fund_pages', page=next_page) }}">Next</a>

Upvotes: 2

Related Questions