这是我的烧瓶应用程序运行在谷歌应用程序引擎,下面的代码是我的一点视图.py文件。我所要做的就是在它自己的页面上显示存储的数据库信息,URL是ID
@app.route('/')
def list_posts():
posts = Post.all()
return render_template('list_posts.html', posts=posts)
@app.route('/posts/<int:id>')
def display_posts(id):
posts = Post.all()
return render_template('display_posts.html', posts=posts)
这是我的模板:
{% extends "base.html" %}
{% block content %}
<ul>
<h1 id="">Posts registered on the database</h1>
<li>
{{ post.title }} (written by {{ post.author.nickname() }})<br />
{{ post.content }}
</li>
</ul>
{% endblock %}
这是我得到的错误:
<class 'jinja2.exceptions.UndefinedError'>: 'post' is undefined
Traceback (most recent call last):
File "/base/data/home/apps/s~smart-cove-95709/1.384716942984350887/main.py", line 4, in <module>
run_wsgi_app(app)
File "/base/data/home/runtimes/python/python_lib/versions/1/google/appengine/ext/webapp/util.py", line 99, in run_wsgi_app
run_bare_wsgi_app(add_wsgi_middleware(application))
File "/base/data/home/runtimes/python/python_lib/versions/1/google/appengine/ext/webapp/util.py", line 117, in run_bare_wsgi_app
result = application(env, _start_response)
File "/base/data/home/apps/s~smart-cove-95709/1.384716942984350887/flask/app.py", line 874, in __call__
return self.wsgi_app(environ, start_response)
File "/base/data/home/apps/s~smart-cove-95709/1.384716942984350887/flask/app.py", line 864, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/base/data/home/apps/s~smart-cove-95709/1.384716942984350887/flask/app.py", line 861, in wsgi_app
rv = self.dispatch_request()
File "/base/data/home/apps/s~smart-cove-95709/1.384716942984350887/flask/app.py", line 696, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/base/data/home/apps/s~smart-cove-95709/1.384716942984350887/blog/views.py", line 26, in display_posts
return render_template('display_posts.html', posts=posts)
File "/base/data/home/apps/s~smart-cove-95709/1.384716942984350887/flask/templating.py", line 81, in render_template
context, ctx.app)
File "/base/data/home/apps/s~smart-cove-95709/1.384716942984350887/flask/templating.py", line 65, in _render
rv = template.render(context)
File "/base/data/home/apps/s~smart-cove-95709/1.384716942984350887/jinja2/environment.py", line 891, in render
return self.environment.handle_exception(exc_info, True)
File "/base/data/home/apps/s~smart-cove-95709/1.384716942984350887/blog/templates/display_posts.html", line 1, in <module>
{% extends "base.html" %}
两个
render_template
调用都只传递posts
对象:但是,您的模板仅引用单数
post
:因此,当jinja试图呈现模板时,它会尝试使用存储在变量
post
中的内容填充占位符,但是没有占位符。你知道吗因此,要使此模板正常工作,您必须向模板传递一个单一的
post
,例如:但是,按照您编写模板的方式,在一个列表中显示多篇文章更有意义。因此,在这种情况下,您应该传递一个post列表作为
posts
——就像您现在所做的那样,但是更改模板以迭代该列表并为该列表中的每个post生成输出:/posts/<id>
路由应该是这样工作的:注意,我们只传递一个post,所以模板应该只需要一个post。通过在变量名、方法名和模板名中使用单数或复数(例如
display_post
、display_post.html
、和post
与list_posts
、list_posts.html
、和posts
),您应该始终尝试弄清楚您谈论的是单个对象还是多个对象。你知道吗相关问题 更多 >
编程相关推荐