I have:
from flask import Flask, render_template
import datetime
app = Flask(__name__)
@app.route("/")
def hello():
now = datetime.datetime.now()
timeString = now.strftime("%Y-%m-%d %H:%M")
templateData = {
'title' : 'HELLO!',
'time': timeString
}
return render_template('main.html', **templateData)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80, debug=True)
and html:
<!DOCTYPE html>
<head>
<title>{{ title }}</title>
</head>
<body>
<h1>Hello, World!</h1>
<h2>The date and time on the server is: {{ time }}</h2>
</body>
</html>
Is possible on flask create a button to post in a flask function on the same page? Thank
So your form code can look something like this (this is just an example):
<form method='POST' action="/">
<p>username: <input type="text" name="username"/></p>
<p>password: <input type="password" name='password'/></p>
<p><input type="submit" value="Login" style="width: 100px; height: 100px;"/></p>
</form>
action="..." should be the path you want to post to. So if we wanted to post to "/" path we can do the above and catch it in your code by using the following:
@app.route('/', methods=['GET', 'POST'])
def hello():
if request.method == 'POST':
.... # Add whatever code you want to execute if it is a post request
now = datetime.datetime.now()
timeString = now.strftime("%Y-%m-%d %H:%M")
templateData = {
'title' : 'HELLO!',
'time': timeString
}
return render_template('main.html', **templateData)
We need to change the app.route part because we have to specify we can reach this route via a Get request or a Post request. We can check if it is a Post request by using if request.method == 'POST':
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With