mengu on web programming.

Pagination With WebPy

You know that I have been dealing with major frameworks like Django or Ruby on Rails. However I have decided to learn werkzeug and webpy too. Currently learning webpy. A user on freenode #webpy asked how to implement pagination with webpy and here i explain how to do it. Let's start with the logic first. * page should be either in the query string or 1. * perpage option should be set. * offset will be calculated with ((page - 1) * perpage). * total page number will be found by (total data count / perpage) Here's the deal: class index: def GET(self): params = web.input() page = if hasattr(params, 'page') else 1 perpage = 3 offset = (int(page) - 1) * perpage posts ="post", order="id DESC", offset=offset, limit=perpage) postcount = db.query("SELECT COUNT(*) AS count FROM post")[0] pages = postcount.count / perpage return render.index(posts=posts, session=session, pages=pages) I am using Jinja2 as my template engine so here is how I printed the pages: {% for page in range(pages) %} {% endfor %} Yes, it is that simple! :)
Did you enjoy this post? You should follow me on twitter here.


demoriz said on 20/06/2010 17:52 PM
If postcount.count = 12 and perpage = 5, then 2 items will not get to the page. Solution: pages = postcount.count / perpage if postcount.count % perpage > 0: pages += 1

Mengu Kagan said on 26/06/2010 01:17 AM
Thank you demoriz, let me update the post when I've got some free time. :)

Siros said on 09/06/2012 20:55 PM
Thank you ! It would be great if you could explain how to use this feature with *reusability* in mind.

Leave a Response

No HTML allowed. You can use markdown.
E-Mail* (not published):
Web site: