Form data saving help!

Question:
Hi guys, using Flask, I need some help in creating a form where the user inputs their name and email, and the form data is then stored on a variable on Python. Does anyone know how to do it? It would be a great help. Thanks.
(I deleted the other sections since those are unimportant in this question)

I need help with this, can anyone help me? Quick.

Create a Flask application with a route for the form:

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def form():
    name = None
    email = None
    if request.method == 'POST':
        name = request.form.get('name')
        email = request.form.get('email')
    return render_template('form.html', name=name, email=email) #I named the file as form.html but you can change this to the name of your actual HTML file.

if __name__ == '__main__':
    app.run(debug=True)

Remember that you need to create a folder in your project named “templates”, your HTML file goes there and your HTML must have a method="POST" in the form to Python fetch the data.

2 Likes

So I need to put in the <form></form>tag in the HTML file?

Yes.

Giving a further example with the HTML file:

    <body>
        <form method="POST"> //As I said the method of the form must be POST.
            <label for="name">Name:</label><br>
            <input type="text" id="name" name="name" value="{{ name }}"><br>
            <label for="email">Email:</label><br>
            <input type="text" id="email" name="email" value="{{ email }}"><br>
            <input type="submit" value="Submit">
        </form>
        {% if name and email %}
            <p>Name: {{ name }}</p>
            <p>Email: {{ email }}</p>
        {% endif %}
    </body>
2 Likes

@WindLother So I put form.html in a folder called ‘templates’?
Why do I need the folder?

Soo… I created a form.html file and put that in a folder called ‘templates’, and it doesn’t work…

Because of their documentation:
https://python-adv-web-apps.readthedocs.io/en/latest/flask3.html

“A proper Flask app is going to use multiple files — some of which will be template files. The organization of these files has to follow rules so the app will work. Here is a diagram of the typical structure:”

2 Likes

So… I organised it wrongly?

You have to follow the exact strucuture as above.

Your main.py must be outside the templates folder and the form.html inside the templates folder.

After you organized everything just run the project.

If you are having any errors just paste them here.

2 Likes

That’s exactly what I did! However, although there’s no errors, the Webview tab does not open.

That’s because you are not exposing the http server.

In your main.py just change this line:

if __name__ == '__main__':
    import os
    app.run(host='0.0.0.0', port=int(os.getenv('PORT', 8080)))

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.