Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask post to the same page

Tags:

python

html

flask

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

like image 219
fabrizio bianchi Avatar asked May 11 '26 13:05

fabrizio bianchi


1 Answers

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.

like image 170
sebenalern Avatar answered May 13 '26 02:05

sebenalern