I have a form where a user logs in with a google account and then makes or updates their profile in google app engine. I want to use the form field that contains their email address (which is automatically filled in with their user info from google) as the new entry's key. This way I can easily update the entries since as long as they have the same email they will be the same entry. Here is my form model and my page post and get methods, how can I modify them to set the key?
class Athlete(db.Model):
#fields to be added to the form
norse_key = db.UserProperty()
key_name = norse_key
first_name = db.StringProperty()
last_name = db.StringProperty()
school_class = db.StringProperty()
sex = db.StringProperty()
home_address = db.StringProperty()
city = db.StringProperty()
state = db.StringProperty()
zip = db.IntegerProperty()
residence = db.StringProperty()
SPO = db.IntegerProperty()
cell = db.IntegerProperty
sport_1 = db.StringProperty()
sport_2 = db.StringProperty()
sport_3 = db.StringProperty()
class AthleteForm(djangoforms.ModelForm):
class Meta():
model = Athlete()
class AthleteFormPage(webapp.RequestHandler):
def get(self):
user = users.get_current_user()
self.response.out.write((user))
query = db.GqlQuery("SELECT * FROM Athlete WHERE norse_key = :1", user)
item = None
for item in query:
self.response.out.write("%s,%s<br>" % (i开发者_运维技巧tem.norse_key,item.first_name))
self.response.out.write('<div style="float:right"><a href="%s">Log Out</a> </div >'% (users.create_logout_url("/")))
self.response.out.write('<html> <body> <a href="/">Submit A Treatment Log</a> <form method="POST" action="/athleteformpage.html"> <table>')
if item != None:
self.response.out.write(AthleteForm(initial={'norse_key':item.norse_key,'first_name':item.first_name}))
else:
self.response.out.write(AthleteForm(initial={'norse_key':user}))
self.response.out.write('</table> <input type="submit"> </form> </body> </html>')
def post(self):
data = AthleteForm(data=self.request.POST)
if data.is_valid():
# Save the data, and redirect to the view page
entity = data.save(commit=False)
entity.added_by = users.get_current_user()
entity.put()
self.redirect('/athletes.html')
else:
# Reprint the form
self.response.out.write('<html><body> <form method="POST" action="/athleteformpage.html"> <table>')
self.response.out.write(data)
self.response.out.write('</table> <input type="submit"> </form></body></html>')
Every entity in GAE datastore has a key, the key can be an id or string.
When creating an entity you can specify which value the key will have using the key_name atribute. for example:
Athlete.get_or_insert(key_name=name, ....)
You can remove the key_name that you put in your model and use the one that comes "out of the box"
to query for an entity using a key_name use Athlete.get_by_key_name(name)
.
Due notice that key is case sensitive so you probbely need to make it canonical (by lower casing it and also probably url decoding it)
精彩评论