Reputation:
I have a template (index.html
) that I would like to display on GET
and the same template, with a variable added, on POST
.
app.py:
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def hello():
return render_template("index.html")
@app.route("/", methods=["POST"])
def hello_():
return render_template("index.html", string_="Success!")
if __name__ == "__main__":
app.run(host='0.0.0.0', port=4567)
index.html:
<html>
<head>
<script type="text/javascript" src="/static/jquery.js"></script>
</head>
<body>
<button onclick="signIn();">Sign In</button>
<h1>{{ string_ }}</h1>
<script>
function signIn() {
var data = "data";
$.ajax({
type : "POST",
data: JSON.stringify(data, null, '\t'),
contentType: 'application/json',
success: function(result) {
console.log(result);
}
});
}
</script>
</body>
</html>
traceback:
* Running on http://0.0.0.0:4567/ (Press CTRL+C to quit)
127.0.0.1 - - [11/Dec/2015 11:16:17] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [11/Dec/2015 11:16:17] "GET /static/jquery.js HTTP/1.1" 304 -
127.0.0.1 - - [11/Dec/2015 11:16:21] "POST / HTTP/1.1" 200 -
I'm not receiving an error, but the variable string_
isn't appearing in the template on POST
(after I click the button). It appears that the template I have set to render on POST
isn't working.
Is it possible to render a different template in Flask based on request.method
?
Upvotes: 3
Views: 7586
Reputation: 106450
It makes the most sense to split this into two distinct routes, one serving the GET
and one serving the POST
.
@app.route('/')
def index_as_get():
return render_template('index.html', name="")
@app.route('/', methods=["POST"])
def index_as_post():
r = request.get_json()
name = r['name']
return render_template('index.html', name=name)
Note that you actually have to invoke this behavior through a REST client that can invoke a POST request to your root page before you can notice anything.
Upvotes: 1