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
- AppEngine Forms in Python
- Submit AppEngine Forms Using POST in Python
- AppEngine Edit Form in Python
- 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.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
def post(self): data = MyForm(data=self.request.POST) if data.is_valid(): # Save data entity = data.save(commit=False) entity.put() # Redirect somewhere self.redirect('/') else: # Reprint the formProgramming Language: Python
I did put the form in separate function so I wouldn't have to type it twice.Source code viewer
import os from google.appengine.ext import webapp, db from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext.db import djangoforms class MyModel(db.Model): title = db.StringProperty(required=True) type = db.StringProperty(choices=['Earth','Dark','Light','Water','Fire','Wind','Divine']) year = db.IntegerProperty() review = db.TextProperty() class MyForm(djangoforms.ModelForm): class Meta: model = MyModel class MainPage(webapp.RequestHandler): def get(self): self.form() def post(self): data = MyForm(data=self.request.POST) if data.is_valid(): entity = data.save(commit=False) entity.put() self.redirect('/') else: self.form() def form(self): self.response.out.write('<html><body>' '<form method="POST" action="/">' '<table>') self.response.out.write(MyForm()) self.response.out.write('</table>' '<input type="submit">' '</form></body></html>') application = webapp.WSGIApplication( [('/', MainPage)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()Programming Language: Python
Now the form data submission is ready.