Reputation: 17
I am new to Google App Engine and datastore so please be patient :)
My code below is trying to ask for user inputs, either entering or deleting an entry, and the results will be shown directly in a table on the same page. When I tried to delete a particular entry in the datastore, the row does not get deleted in the datastore and sometimes new rows with empty data are added. Why does this happen?
class Events(ndb.Model):
name = ndb.StringProperty()
desc = ndb.StringProperty()
class Promote(webapp2.RequestHandler):
def get(self):
query = ndb.gql("SELECT * "
"FROM Events "
)
template_values = {"events" : query,}
template = jinja_environment.get_template('promote.htm')
self.response.out.write(template.render(template_values))
def post(self):
event = Events(name = self.request.get('name'), desc = self.request.get('desc'))
event.put()
self.redirect('/promote')
class Delete(webapp2.RequestHandler):
def post(self):
event = ndb.Key('Events', self.request.get('eventname'))
event.delete()
self.redirect('/promote')
app = webapp2.WSGIApplication([('/', Main),
('/publicsearch', PublicSearch),
('/promote', Promote),
('/delete',Delete)],
debug=True)
This is the html code
<div class="jumbotron">
<div class = "container">
<form action="/promote" method="post">
<fieldset>
<div class="row-fluid">
<p> Promote your event here! </p>
<div class="row-fluid">
<div class="span6">
<p> Name of event: <br>
<textarea class="input-block-level" name="name" rows="1" cols = "50"> </textarea></p>
<p> Event description: <br>
<textarea class="input-block-level" name="desc" rows="3" cols = "50"> </textarea></p>
<p><input type="submit" value="Submit">
</div>
</div>
</div>
</div>
</div>
<h4> Events feed </h4>
<table class="table table-bordered table-striped">
<thead>
<tr>
<th width="30%">Name</th>
<th width="60%">Description</th>
<th>Delete Event</th>
</tr>
</thead>
<tbody>
{% for event in events %}
<tr>
<td>{{ event.name }} </td>
<td>{{ event.desc }} </td>
<td>
<form action="/delete" method="post">
<input type="hidden" name="eventkey" value="{{ event.key.urlsafe() }}">
<input type="submit" value="Delete">
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
Thanks!
Upvotes: 0
Views: 179
Reputation: 599490
The key is not based on the event name, because you haven't specified any key when creating the events: they'll just use a numeric id.
The better thing to do here would be to put the actual key in the hidden input: you can use the urlsafe
method to output a string that can be used in templates.
<input type="hidden" name="eventkey" value="{{ event.key.urlsafe() }}">
and in the view:
event = ndb.Key(urlsafe=self.request.get('eventkey'))
Upvotes: 2