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> {{=BEAUTIFY(response._vars)}} {{ for x in people: }} Show Addresses for: {{=A(x.name, _href=URL('showHouses?id=' + str(x.id)))}} {{=BR()}} {{ pass }} ---- end houses/display.html ---- start houses/saveAddress.html {{=BEAUTIFY(response._vars)}} ---- 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> </div> <script> ajax('saveAddress',['owner'],'houseListing'); </script> ---- 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'.
0
icreator 5 years ago
nice example!
0
derek-wilson-10759 7 years ago
I just wanted to add - this is just an example, it is not secure AS-IS. You would want to prevent double submits, and CSRF by implementing your own formkey in session.
0
derek-wilson-10759 7 years ago
Hope it makes sense, this was one of the easiest ways I found to do this, and web2py does make it very simple. I only wish there were a way to load a different function (view) than the one posted to. In any case, this does the job.