views:

36

answers:

2

Assuming I have the following:

class Person(db.Model):
  name = db.StringProperty()

I would like to print all the names in an html file using a template.

template_values = {'list': Person.all()}

And the template will look like this:

{% for person in list %}
<form>
  <p>{{ person.name}} </p>
  <button type="button" name="**{{ person.id }}**">Delete!</button>
</form>
{% endfor %}

Ideally I would like to use person.key or person.id to then be able to delete the record using the key but that doesn't seem to work. Any Ideas how can I accomplish this?

+2  A: 

Use {{person.key.id}}, not just {{id}}. This will call each object's .key().id() method(s).

However, you should also be aware that passing Person.all() as a template value isn't necessarily a great idea; .all() returns a db.Query object, which can be treated as an iterable like you're doing but which will do multiple RPCs as you iterate through the query; instead you should use something like Person.all().fetch(SOME_NUMBER), where SOME_NUMBER is a reasonable amount to display to the user (or an arbitrarily large number if you insist on trying to display everything in one view.)

Wooble
Hi I tried person.id as I mentioned in the question (last sentence) but it returned an empty string. I edited the name of variable to avoid confusion.
Luis Benavides
edited; you need .key().id(); id() isn't a method of the entity at all.
Wooble
+1  A: 

Found the solution in one of the code samples:

template_values = {'list': **list**(Person.all())}

And in the template:

{% for person in list %}
<form>
  <p>{{ person.name}}</p>
  <button type="button" name="**{{ person.key }}**">Delete!</button>
</form>
{% endfor %}

As Wooble recommended, you may want to try Person.all().fetch(SOME_NUMBER) instead.

Luis Benavides