Search code examples
pythonhtmlflaskweb-applications

Print a text of textbox in HTML with Flask after pressing a button


This is my first exercise in Flask and I would like to understand what I am doing wrong here.

I want to insert a text in a textbox and then visualize it in HTML I have already looked many answers on StackOverflow, including this: Set a python variable in flask with a button and javascript

This is my python code:

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route("/")
def my_form():
    return render_template('test.html')

@app.route("/", methods=['GET','POST'])
def func_test():
    if request.method == 'POST':
        text = request.form['Value1']
        return render_template('test.html', value1=text)

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

and this is my HTML:

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form methods="POST">
<p>Login </p><br>
    <p>Value1 <input type = "text" name = "Value1" /></p>
    <p><input type = "submit" value = "submit" name = "submit" /></p>

</form>
input is {{value1}}
</body>
</html>

What I would like is that after the text is written in the textbox and the button is pressed, the text is printed after input is

Thanks


Solution

  • well, you can wrap your txt result in an if block that only shows when there is value

       {% if value %}
       input is {{value1}}
       {% else %}
        input is: 
        {% endif %}
    
        <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <form method="POST">
    <p>Login </p><br>
        <p>Value1 <input type = "text" name = "Value1" /></p>
        <p><input type = "submit" value = "submit" name = "submit" /></p>
    
    </form>
    input is {{value1}}
    </body>
    </html>