Search code examples
pythondatabaseweb2py

Using SQLFORM.grid & request.args


At the moment I am displaying selected data in a database with a HTML table.

default.py:

def show():
post = db.games(request.args(0))
reviewRows = db(db.reviews.game_id == request.args(0)).select()
return locals()

show.html

{{extend 'layout.html'}}

<h2>{{=post.title}}</h2>

<i>Desc: {{=post.description}}</i>

<h2>Reviews:</h2>
<table class="table">
    <tr>
        <th>Review title</th>
        <th>Review</th>
    </tr>
    {{for row in reviewRows:}}
    <tr>
        <td>{{=row.title}}</td>
        <td>{{=row.review}}</td>
    </tr>
    {{pass}}
</table>

But I would like to use a SQL.grid so that I can sort & search the table.

I have tried

reviewRows = SQLFORM.grid(db.reviews.game_id == request.args(0)).select()

But this just links me back to the index page. I'm assuming its because its not taking the argument correctly?

default.py:

def index():
    gridHome = SQLFORM.grid(db.games, editable=False, create=False, csv=False, deletable=False, details=False, links = [lambda row: A('View Post',_href=URL("default","show",args=[row.id])), lambda row: A('Review',_href=URL("default","review",args=[row.id]))])
    return locals()

Solution

  • SQLFORM.grid uses the URL args to construct its own URLs, so if the base URL of the grid action already uses one or more URL args, you must specify this via the args argument:

    reviewRows = SQLFORM.grid(db.reviews.game_id == request.args(0), args=request.args[:1])
    

    The above tells the grid that all internal URLs it constructs should include request.args[:1] as a URL arg before adding any of its own URL args.

    Also, note that you should not add a .select() to SQLFORM.grid as you have in your example code.