views:

183

answers:

2

I tried the following code and it didn't work:

class SourceUpdate(webapp.RequestHandler):
  def post(self):
    id = int(self.request.get('id'))
    source = Source.get_by_id(id)
    for property in self.request.arguments():
      if property != 'id':
        source.__dict__[property] = self.request.get(property)
    source.put()
    self.redirect('/source')

I am posting all the necessary properties but the entry isn't updated, and no error is shown. How to fix it?

BTW

class Source(db.Model):
  #some string properties
+2  A: 

You're bypassing the __setattr__-like functionality that the models' metaclass (type(type(source))) is normally using to deal with attribute-setting properly. Change your inner loop to:

for property in self.request.arguments():
  if property != 'id':
    setattr(source, property, self.request.get(property))

and everything should work (if all the types of properties can be properly set from a string, since that's what you'll get from request.get).

Alex Martelli
It works! Thanks man!
Jader Dias
+2  A: 

Instead of directly setting model values from the request, you might want to look into using Django forms. They're bundled with App Engine, and facilitate validating form data and storing it in the datastore, as well as generating the form HTML. There's an article on how to use them with the App Engine datastore here.

Also, don't forget that making changes based on a GET request is almost always a bad idea, and leads to XSRF vulnerabilities and other problems!

Nick Johnson