16 August 2010

Second part of AppEngine Forms. This time we will try to get our data through post and save the data to database.

Basic Form Tutorial Google AppEngine

  1. AppEngine Forms in Python
  2. Submit AppEngine Forms Using POST in Python
  3. AppEngine Edit Form in Python
  4. Delete Row From Datastore in AppEngine

This time we will try to get our data through post and save the data to database.

Getting The Forms Data:

Now that we have the model and form done and printed on the screen we want to take the data from the form and save it. We are using POST method.
Source code viewer
  1. def post(self):
  2. data = MyForm(data=self.request.POST)
  3. if data.is_valid():
  4. # Save data
  5. entity = data.save(commit=False)
  6. entity.put()
  7. # Redirect somewhere
  8. self.redirect('/')
  9. else:
  10. # Reprint the form
Programming Language: Python
The Model will be written to database. The submission reminds me how you save data in LINQ. Here is the full code:
Source code viewer
  1. import os
  2. from google.appengine.ext import webapp, db
  3. from google.appengine.ext.webapp.util import run_wsgi_app
  4. from google.appengine.ext.db import djangoforms
  5.  
  6. class MyModel(db.Model):
  7. title = db.StringProperty(required=True)
  8. type = db.StringProperty(choices=['Earth','Dark','Light','Water','Fire','Wind','Divine'])
  9. year = db.IntegerProperty()
  10. review = db.TextProperty()
  11.  
  12. class MyForm(djangoforms.ModelForm):
  13. class Meta:
  14. model = MyModel
  15.  
  16. class MainPage(webapp.RequestHandler):
  17. def get(self):
  18. self.form()
  19. def post(self):
  20. data = MyForm(data=self.request.POST)
  21. if data.is_valid():
  22. entity = data.save(commit=False)
  23. entity.put()
  24. self.redirect('/')
  25. else:
  26. self.form()
  27. def form(self):
  28. self.response.out.write('<html><body>'
  29. '<form method="POST" action="/">'
  30. '<table>')
  31. self.response.out.write(MyForm())
  32. self.response.out.write('</table>'
  33. '<input type="submit">'
  34. '</form></body></html>')
  35.  
  36.  
  37. application = webapp.WSGIApplication(
  38. [('/', MainPage)],
  39. debug=True)
  40.  
  41. def main():
  42. run_wsgi_app(application)
  43.  
  44. if __name__ == "__main__":
  45. main()
Programming Language: Python
I did put the form in separate function so I wouldn't have to type it twice.