繁体   English   中英

render_template() 正好有 1 个参数

[英]render_template() takes exactly 1 argument

当我单击提交以查看以下视图时,我收到了 500 错误。 为什么我会收到此错误以及如何修复它?

from flask import Flask, render_template
from flask import request, jsonify

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def homepage():
    if request.method == 'POST':
        f1 = request.form['firstVerb']
        f2 = request.form['secondVerb']
        return render_template('index.html', f1, f2)
    return render_template('index.html')

if __name__ == "__main__":
    app.run();
<form class="form-inline" method="post" action="">
<div class="form-group">
    <label for="first">First word</label>
    <input type="text" class="form-control" id="first" name="firstVerb">
</div>
<div class="form-group">
    <label for="second">Second Word</label>
    <input type="text" class="form-control" id="second" name="secondVerb" >
</div>
<button type="submit" class="btn btn-primary">Run it</button>
</form>

{{ f1 }}
{{ f2 }}

首先,当您收到 500 错误时,您应该考虑以调试模式运行应用程序。 您正在构建此应用程序,并且在调试时,打开它以显示发生错误时会发生什么非常有用。

if __name__ == "__main__":
    app.run(debug=True)

现在这会让你得到更令人兴奋的东西:

127.0.0.1 - - [08/Jul/2015 14:15:04] "POST / HTTP/1.1" 500 -
Traceback (most recent call last):
...
  File "/tmp/demo.py", line 11, in homepage
    return render_template('index.html', f1, f2)
TypeError: render_template() takes exactly 1 argument (3 given)

这是你的问题。 您应该参考render_template的文档,并看到它实际上只接受一个位置参数(模板名称),但其余参数(在**context )必须作为关键字参数提供。 否则将不会对模板中引用的变量进行引用,因此将该调用修复为:

    return render_template('index.html', f1=f1, f2=f2)

将为模板提供正确的f1f2 ,从而解决手头的问题。

为了将来参考,可以通过阅读Flask 文档来解决此类问题。 另外,请阅读整个 Flask 教程,以帮助您掌握该框架的基础知识。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM