Issue
I I am getting a 500 error when I click submit for the following view. Why am I getting this error and how do I fix it?
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 }}
Solution
First off when you are getting a 500 error you should consider running the app with debug mode. You are building this app and while you are debugging, it is very useful to have this on to show you what happens when an error happens.
if __name__ == "__main__":
app.run(debug=True)
Now this gets you something more exciting:
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)
There is your problem. You should refer to the documentation for render_template
and see that it really only accepts one positional argument (the template name), but the rest of the arguments (in **context
) msut be provided as keyword arguments. Otherwise there would be no references to the variables that were being referred to in the template, so fixing that call to:
return render_template('index.html', f1=f1, f2=f2)
Would provide the correct f1
and f2
to the template, thus solving the problem at hand.
For future reference, problems like these can be solved by reading the Flask documentation. Also, please go through this entire Flask tutorial to help you grasp the basics of this framework.
Answered By - metatoaster
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.