Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Denis Nutiu
650 PointsIs there a clean way to update and pass request.args to url_for() in Flask Jinja2?
I have created a flask app which retrieves results from a database and lists them on a page. Then I added pagination and filtering options.
My pagination design isn't that great and.. I have buttons on my template for next, previous, n-th page. I get the page number and the filtering options from the request.args.
When I am on /?page=2&search=something I want to create a button that when clicked it updates the url to /?page=3&search=something so far I have come up with this:
<li>
<a href="{{ url_for('scoreboard.index', page=pagination[2] + 1,
result_name=request.args.get('result_name')) }}" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
<li>
pagination[2] is the current page, it is passed via the controller and I'm using result_name=request.args.get('result_name') in order to persist the filters.
Is this okay?
1 Answer
Daniel Santos
34,969 PointsAn asynchronous solution, which I am not sure whether is clean or not, will be to have the "next" or "previous" button redirect to the current + 1 page.
I don't know the implementation of your current routing is, but I would have something like:
@app.route("/index")
def index():
try:
next = request.args.get('next')
expect Exception: # Don't remember what exception it throws if can't get the argument.
# No next 'request', do regular stuffs
# return render_template for regular index...
else:
# Generate stuffs for the 'next' page
# return render_template for next index...
<button onclick="getNextPage({{ currentIndex + 1 }})">Next</button>
<script>
function getNextPage(nextIndex) {
var uri = "/index/?next=" + nextIndex
window.location.replace(uri);
}
</script>
If my solution is not beautiful for your eyes (btw I dont like it myself), check the suggested approach from the Flask's snippets collections.
http://flask.pocoo.org/snippets/44/
They basically make an Pagination object, which you can copy and page, that guy you a few functionalities. -Dan
Denis Nutiu
650 PointsDenis Nutiu
650 PointsThank you for your reply! I google pagination before implementing it but I wanted to do my own thing, it's not that good and it looks awful.
Here's my controller:
And here's my index.html