我是Google App Engine和数据存储区的新用户,请耐心等待:)
下面的代码试图询问用户输入,输入或删除条目,结果将直接显示在同一页面的表格中。当我尝试删除数据存储区中的特定条目时,该行不会在数据存储区中被删除,有时会添加具有空数据的新行。为什么会这样?
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)
这是html代码
<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>
谢谢!
答案 0 :(得分:2)
密钥不是基于活动名称,因为您在创建活动时未指定任何密钥:他们只会使用数字ID。
这里更好的做法是将实际的密钥放在隐藏的输入中:您可以使用urlsafe
方法输出可以在模板中使用的字符串。
<input type="hidden" name="eventkey" value="{{ event.key.urlsafe() }}">
并在视图中:
event = ndb.Key(urlsafe=self.request.get('eventkey'))