'Python Flask SQLAlchemy Pagination
I am having trouble implementing pagination with Flask-SQLAlchemy or Flask-Pagination, either or. I am unsure how to initialize the pagination, setting pages, determining pages, offest, etc. I am coming from PHP, quite new to Python.
I am querying all the posts in my database
posts = Posts.query.order_by(Posts.time.desc()).all()
I have been looking at the following examples:
- http://www.ergo.io/tutorials/better-pagination-in-flask/better-pagination-in-flask/
- https://pythonhosted.org/Flask-paginate/
- sqlalchemy pagination
I am confused on really what to do, the information I am finding greatly differs between articles. It's left me with confusion and not knowing where to begin. I want to query all rows of the database table, limit the results to 20 and paginate. I'm not seeing this clearly.
Solution 1:[1]
Controller
@app.route('/', methods=['GET'], defaults={"page": 1})
@app.route('/<int:page>', methods=['GET'])
def index(page):
page = page
per_page = 2
users = User.query.paginate(page,per_page,error_out=False)
# print("Result......", users)
return render_template("index.html", users=users)
in the View
{% for user in users.items %}
<h1> {{ user.name }} </h1>
{% endfor %}
<nav aria-label="Page navigation example">
<ul class="pagination">
{% if users.has_prev %}
<li class="page-item"> <a class="page-link" href="{{ url_for('index', page=users.prev_num) }}">Previous</a></li>
{% else %}
<li class="page-item"><a class="page-link btn disabled" href="#">Previous</a></li>
{% endif %}
{% if users.has_next %}
<li class="page-item"> <a class="page-link" href="{{ url_for('index', page=users.next_num) }}">Next</a></li>
{% else %}
<li class="page-item"><a class="page-link btn disabled" href="#">Next</a></li>
{% endif %}
</ul>
</nav>
Solution 2:[2]
I used @user3186184 code but I got this error:
TypeError: 'Pagination' object is not iterable
But when I add items to the end of these code:
users = User.query.paginate(page,per_page,error_out=False).items
My issue was fixed.
Solution 3:[3]
Here is the simplest answer to add pagination in flask
no_of_posts = 3
page = request.args.get("number")
if page is None:
page = 1
else:
page = int(page)
allPosts = Posts.query.filter_by().all()
length = len(allPosts)
allPosts = allPosts[(page-1)*no_of_posts: page*no_of_posts]
if page > 1:
prev = page -1
else:
prev = None
if page < math.ceil(length/no_of_posts):
next = page + 1
else:
next = None
In the template
{% if prev %}
<a href="?number={{ prev }}">« Previous</a>
{% endif %}
{% if next %}
<a href="?number={{ next }}">Next »</a>
{% endif %}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user3186184 |
| Solution 2 | Abbas Jafari |
| Solution 3 | Lakshyaraj Dash |
