I am trying to delete an entity from the Datastore using a link in html. I understand that in order to do this, I need to have the entity's key so that I know which entity to "pair" the delete link with, so to speak. I can't for the life of me figure out how to do this...
Here is my html file that shows all of the cars in the database:
{% if cars|length > 0 %}
{% for c in cars %}
<tr>
<td>{{ c.make }}</td>
<td>{{ c.model }}</td>
<td>{{ c.year }}</td>
<td>
{% for i in c.color %}
{{ i }}
{% endfor %}
</td>
<td>{{ c.condition }}</td>
<td>{{ c.date }}</td>
<td>
<a href="/view_cars/{{ c.key().id() }}">Delete Car</a>
</td>
</tr>
{% endfor %}
{% endif %}
Here is the python file:
class AddCarHandler(webapp2.RequestHandler):
template_variables = {}
def get(self):
template = JINJA_ENVIRONMENT.get_template('index.html')
self.response.write(template.render(self.template_variables))
action = self.request.get('action')
#if the user adds a car
if action == 'add_car':
c = car_database.Car()
c.make = self.request.get('car-make')
c.model = self.request.get('car-model')
c.year = self.request.get('car-year')
c.color = self.request.get_all('car-color')
c.condition = self.request.get('car-condition')
c.date = self.request.get('car-date')
car_key = c.put()
class ViewCarHandler(webapp2.RequestHandler):
template_variables = {}
def get(self):
car = car_database.Car()
#ndb query
self.template_variables['cars'] = [{'make':x.make, 'model':x.model, 'year':x.year, 'color':x.color, 'condition':x.condition, 'date':x.date} for x in car_database.Car.query().fetch()]
template = JINJA_ENVIRONMENT.get_template('/view_cars.html')
self.response.write(template.render(self.template_variables))
You can get the key of an entity (which, say, is obtained through a query) like this:
Note: this only works after the entity was saved into the DB, not before (i.e.
entity.put()
was called at least once).To pass the key between the python code and URLs or HTML code, from the documentation, you can use a key's url string or a pre-computed deletion url based on that string, passed, for example, in
self.template_variables['cars']
:You'll need to add a handler for such deletion url, in which you'd reconstruct the key as quoted above, then call: