If you benefit from web2py hope you feel encouraged to pay it forward by contributing back to society in whatever form you choose!

I'm beginning with web2py and with help of Gustavo Souza made the following code for pagination (for the ones that doesen't use a grid).

The code below is an easy way to make a pagination just with the limitby option.

Model:

if not "post" in db.tables:
    db.define_table('post',
        Field("title", "string", length=128, default=""),
        Field("contents", "text", length=512, default=""),
        Field("created_on", "date", default=None),
        )

if not db(db.post).count():
    from gluon.contrib.populate import populate
    populate(db.post,25)

Controller:

def posts():
	response.title += ' | Posts'
	if not request.vars.page:
		redirect(URL(vars={'page':1}))
	else:
		page = int(request.vars.page)
	start = (page-1)*10
	end = page*10
	posts = db(db.post).select(orderby=db.post.created_on, limitby=(start,end))
	return dict(posts=posts)

The if  not statement defines that if the user tries to access the list of posts without passing a var, the user will be redirected for the first page of the list.

else gets the page variable that was passed in the URL.

'start' and 'end' defines where to begin and where to end limitby to show 10 posts by time.

Finally, posts makes a db.select() with the limitby args passed in 'start' and 'end' and returns it.

 

View:

{{extend 'layout.html'}}
<table class="table table-striped">
    <thead>
        <tr>
            <th>#</th>
            <th>Title</th>
            <th>Content</th>
            <th>Date</th>
            <th>Edit</th>
            <th>Delete</th>
        </tr>
    </thead>
    <tbody>
    {{for post in posts:}}
        <tr>
            <td>{{=post.id}}</td>
            <td>{{=post.title}}</td>
            <td>{{=post.contents}}</td>
            <td>{{=post.created_on}}</td>
            <td>
                <button class="btn"><i class="icon-edit"></i></button>
            </td>
            <td>
                <button class="btn"><i class="icon-trash"></i></button>
            </td>
        </tr>
    {{pass}}
    </tbody>
</table>

This will return the posts like it was defined in limitby. E.g.: default/index/posts?page=1 will show posts 0-10, default/index/posts?page=2 will show posts 10-20.

<a href={{=URL(vars={'page':int(request.vars.page)-1})}}>Previous</a> |
<a href={{=URL(vars={'page':int(request.vars.page)+1})}}>Next</a>

This is the suggested code for the view for previous/next paginators.

 

Related slices

Comments (1)


Hosting graciously provided by:
Python Anywhere