0
votes

I'm using the App Engine extension of WTForms to generate forms from my datastore models. This works great for adding new entities, but I would also like to be able to use the forms to edit existing entities.

Is it possible to load an existing datastore entity into a form created with model_forms from a GAE datastore model? If so, how do I do this? If not, what approach should I take to accomplish this?

1

1 Answers

0
votes

This is my version of updating the google datastore.

class AdminBlogEdit(MethodView):
    def __init__(self):
            self.blog_form = NewBlogEntryForm(csrf_enabled=False)

    def get(self,blog_key_id=None):
        if blog_key_id:
            self.blog_model = BlogEntryModel.get_by_id(blog_key_id)
            self.blog_form = NewBlogEntryForm(obj = self.blog_model)

        return render_template('admin/blog_edit.html', form=self.blog_form)

    def post(self,blog_key_id=None):
        if self.blog_form.validate():
            self.update_post(blog_key_id)
            self.blog_model.put()
            return redirect(url_for(".admin"))
        else:
            return render_template('admin/blog_edit.html', form=self.blog_form)     
        return redirect(url_for(".admin"))


    def update_post(self,blog_key_id):
        if blog_key_id: 
            self.blog_model = BlogEntryModel.get_by_id(blog_key_id)
            self.blog_form.populate_obj(self.blog_model)    
        else:
            self.blog_model = BlogEntryModel(title  =   self.blog_form.title.data, date_created = self.blog_form.date_created.data, 
                                                            entry = self.blog_form.entry.data)

The main idea is to retrieve the datastore entity and fill the form data, before displaying the GET request.

For the PUT request, retrieve the data store entity again and update it with the form data and then call the datastoremodel.put() on it