Flask Tutorial Series #4: Exploring Forms, POST Requests, and File Handling

Posted by


In this tutorial, we will be discussing how to handle forms, POST requests, and file handling in Flask. Forms are an essential component in web development as they allow users to input data that can be submitted to the server. We will be using Flask, a lightweight web framework, to build our application.

Let’s start by creating a new Flask application. Make sure you have Flask installed on your system. You can install it by running pip install Flask in your terminal. Once you have Flask installed, create a new file called app.py and add the following code:

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

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

In this code, we have created a basic Flask application with a single route that renders a template called index.html. Now let’s create the index.html template. Create a new folder called templates in the same directory as your app.py file, and inside the templates folder, create a new file called index.html with the following code:

<!DOCTYPE html>
<html>
<head>
    <title>Flask Form</title>
</head>
<body>
    <h1>Flask Form Example</h1>
    <form method="post" enctype="multipart/form-data">
        <input type="text" name="username" placeholder="Enter your username"><br><br>
        <input type="file" name="file"><br><br>
        <button type="submit">Submit</button>
    </form>
</body>
</html>

In this template, we have created a simple form with an input field for the username and a file input field. The form is set to use the POST method and enctype multipart/form-data which is required for file uploads.

Now let’s update our app.py file to handle the form submission. Add the following code to your app.py file:

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        username = request.form['username']
        file = request.files['file']

        if file:
            file.save(file.filename)
            return f'File uploaded successfully. Username: {username}'

    return render_template('index.html')

In this code, we have updated the index route to handle both GET and POST requests. When a POST request is made, we retrieve the username from the form data and the file from the file input field. We save the file to the current directory with the filename as provided by the user and return a success message with the username.

Now when you run your Flask application and access it in your browser, you should see the form that allows you to enter a username and upload a file. When you submit the form, the file will be saved in the current directory with the filename provided by the user.

That’s it for this tutorial on handling forms, POST requests, and file uploads in Flask. I hope you found this tutorial helpful! Feel free to explore more advanced form handling techniques and customization options in Flask. Happy coding!

0 0 votes
Article Rating
17 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@okkaraung9512
30 days ago

advanced series pls

@dilansarith2188
30 days ago

Thank you very much. your gave a lot of information from one video

@fusebox9725
30 days ago

ValueError: source code string cannot contain null bytes

@fusebox9725
30 days ago

Perhaps, we can write multiple in the input tag so that the site accepts multiple formats, also, required is a built-in thing in html, and doesn't need to be defined.

Btw, SOLID playlist, THANK YOU SO MUCH, Neural Nine!!

@rezaghasemzadeh9440
30 days ago

I like your voice, your character, your everything

@Newb1eProgrammer
30 days ago

"I hate javascript"
I love being part of the python gang, not gonna lie

@DemoAccount-hi4st
30 days ago

It says one positional aergument is missing 'path'

@Playful_minds_
30 days ago

Much appreciated

@remirzae
30 days ago

nice

@leonardomoreiralouzas3995
30 days ago

Very good

@digvijaytaunk
30 days ago

Thanks for the great video. Appreciate if you could also include how to draw data science data visualisation plots and graphs in frontend using flask with any of these matplotlib/plotly/seaborn or any of your favourite library. thanks in advance

@13antonispao
30 days ago

Thanks man, I really appreciate the effort you are putting in this series!

@bogdanmilovanovic3985
30 days ago

Super video, thank you!

@walidazouz3563
30 days ago

thank you also definitely we need more

@vishnubalaji9500
30 days ago

need separate video for javascript 😂

@Erikdexter31
30 days ago

nice 🤝🏻

@JustJacob-kt
30 days ago

Appreciate you N9, keep it up