Can't render data from GAE datastore with Jinja2
I can't realize what I do wrong. I have some entries in GAE datastore. I have Jinja2 imported. I want to show datastore entries on the page using Jinja2. I have created a shortcut function to call Jinja2 render function. It looks like this:
def render_template(response, template_name, vars=dict()):
template_dirs = [os.path.join(root(), globals['templates_root'])]
env = Environment(loader=FileSystemLoader(template_dirs))
try:
template = env.get_template(template_name)
except TemplateNotFound:
raise TemplateNotFound(template_name)
content = template.render(vars)
response.response.out.write(content)
So, only thing I have to pass to this function is a template file name and a dictionary with variables if present. I call this function like this:
class MainHandler(webapp.RequestHandler):
def get(self, *args, **kwargs):
q = db.GqlQuery("SELECT * FROM Person")
persons = q.fetch(20)
utils.render_template(self, 'persons.html', persons)开发者_JS百科
The model Person
looks like this, nothing fancy there:
class Person(db.Model):
first_name = db.StringProperty()
last_name = db.StringProperty()
birth_date = db.DateProperty()
When I try to pass persons
dictionary to render_template
, it throws an error:
TypeError: cannot convert dictionary update sequence element #0 to a sequence
And it doesn't render. When I pass empty {}
as persons
argument, it renders, but obviously without my data.
What do I do wrong? I am sure there is something small I missed but I have no idea what exactly. Thanks!
You're passing a list of entities to your render_template
function instead of passing a dict. Try something like utils.render_template(self, 'persons.html', {'persons': persons})
精彩评论