Search code examples
pythondatabaseweb2py

Web2Py getting/posting values


I'm fairly new to Web2Py and i'm hoping for some help.

I have a reviews DB and a games DB.

At the moment the user can click on a game from a list and they are taken to a page allowing them to leave a review.

I can save the review into the DB but I can't get it to reference the corresponding game.

DB:

db.define_table('games',
            Field('title',requires=IS_NOT_EMPTY()),
            Field('description','text',requires=IS_NOT_EMPTY()))

db.define_table('reviews',
            Field('title',requires=IS_NOT_EMPTY()),
            Field('review','text',requires=IS_NOT_EMPTY()))

Default.py:

def review():
getTitle = db.games(request.args(0)) or redirect(URL('default', 'index'))
formReview = SQLFORM(db.reviews,fields = ['title','review']).process()
if formReview.accepted: redirect(URL('index'))
return dict(formReview=formReview, getTitle=getTitle)

Review.html:

{{extend 'layout.html'}}
<h2>Review a game</h2>
<h2>{{=getTitle.title}}</h2>
{{=formReview}}

I'm guessing I need to create a field in 'reviews' that will get the 'request.args' value. But i'm not sure?


Solution

  • You should first expand your review table to hold a foreign key to the games table like this:

    db.define_table('reviews',
                Field('title',requires=IS_NOT_EMPTY()),
                Field('review','text',requires=IS_NOT_EMPTY()),
                Field('game_id', 'reference games'))
    

    So you have a reference for which game the review is. With this aditional information you should be able to select all reviews for a game and render them in the view.

    for row in db(db.reviews.game_id == 1).select():
        print row.title   # just an example
    

    And of course you also need to save the corresponding game_id when creating a new review entry ;)

    formReview = SQLFORM(db.reviews,fields = ['game_id', 'title','review']).process()