Here is an example of an HTML form: <form action="/on_add_person" method="get"> <div>first:<input type="text" name="first"></div> <div>last:<input type="text" name="last"></div> <div><input type="submit" value="Add Person"></div> </form> If this form were rendered in a browser, and the user typed in a name, it would look like: When the user clicks on the 'Add Person' button, a request will be made to the server. If we assume the HTML above is from the page http://sample.com/, then the request will be an HTTP GET and effectively the same as if the user had entered, in a browser: http://sample.com/on_add_person?first=Joe&last=Smith App Engine Python ControllerWith App Engine, your controller code must map the action to a controller class method. This is done when your application is created:application = webapp.WSGIApplication( [('/', MainPage), ('/on_add_person', AddPersonHandler) ], debug=True) For this example, the /on_add_person action is mapped to an AddPersonHandler. Once the mapping is set, the controller method can then access the parameters of the request and perform some computation. Parameters of a request are accessed through App Engine's web API and in particular the self.request.get method. So for the above action, the controller might grab the entered first and last name with: class AddPersonHandler(webapp.RequestHandler): Note that the handler must have a get method to match the 'get' specified in the HTML form.def get(self): first=self.request.get('first') last=self.request.get('last') # do some computations, access database # set up template values # render a new page Text Forms with previously set or default dataIn the form above, the values of first and last began as empty, as they should when a new user is registering. When the user is editing previously set data, however, you want the form to appear with that data being displayed.For input boxes of type text, you set the 'value' attribute: <form action="/on_update_person" method="get"> <div>first:<input type="text" name="first" value = {{person.first}}></div> <div>last:<input type="text" name="last" value={{person.last}} ></div> <input type="hidden" name="personkey" value={{person.key}}> <div><input type="submit" value="Update"></div> </form> Here we set the first, last, and key fields from a template variable called 'person'-- the controller will have set this variable as the person being edited. The key field is set so that we can get the person object again in the /on_update_person action. In that controller method, we can do the following: key=self.request.get('key') person = Person.get(key) person.first=self.request.get('first') person.last=self.request.get('last') person.put() Other input typesThe above example is for text input, but HTML provides a number of other input widgets including radio buttons, checkboxes, and drop down listboxes. Check out this tutorial from http://www.w3schools.com/html/html_forms.asp for details. |
