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

Here's how your database should be setup:

db.define_table('person', Field('name'),Field('age','integer'))
db.define_table('house',Field('address'),Field('person', db.person))

And here's how your controllers should be setup (i created a new one called houses.py)...

def index(): 
    return dict(message="hello from houses.py")

def display():
    people = db().select(db.person.ALL)

    return dict(people = people)

def showHouses():
    houses = db(db.house.person == request.vars.id).select(db.house.ALL)
    return dict(houses=houses)

def saveAddress():
        if request.post_vars.address:
            newhouse = db.house.insert(address=request.post_vars.address, person=request.post_vars.owner)
        houses = db(db.house.person == request.post_vars.owner).select(db.house.ALL)
        return dict(houses=houses)

You'll also have to create the views like so:

---- start houses/display.html
{{extend 'layout.html'}}
<h1>This is the houses/display.html template</h1>
{{ for x in people: }}
Show Addresses for: {{=A(x.name, _href=URL('showHouses?id=' + str(x.id)))}}
{{ pass }}

---- end houses/display.html
---- start houses/saveAddress.html
---- end houses/saveAddress.html
---- start houses/showHouses.html
{{extend 'layout.html'}}
<h1> Showing houses for person #{{=request.vars.id}}</h1>

<div id="houseListing"></div>
<div id="input"><input type="text" name="address"/><input type="hidden" name="owner" value="{{=request.vars.id}}" />
    <button onclick="ajax('saveAddress', ['address', 'owner'], 'houseListing')"> Web2PY save </button>
---- end houses/showHouses.html

and then give it a try. You'll have to manually add a 'person' before you can add an address.


How it works is the 'ajax()' call which comes with the web2py.js. The ajax(arg1, arg2, arg3) call will post to arg1, using data from arg2 (getting values for each of the named items in the list), and inserting the results of that call into the innerHTML of arg3. So, I'm using it here as a way to save an address to a person, and to display the addresses that are associated with a person. The 'showHouses' last script tag which calls ajax('saveAddress', ['owner'], 'houseListing') just loads the listing of houses when the page loads. Since there is no 'address' included in the call, the saveAddress function just returns the list of houses for that 'owner'.



Related slices

Comments (3)

Hosting graciously provided by:
Python Anywhere