Welcome back to CodeYourCraft! Today, we're diving into a fascinating topic - Form Data using Flask's request.form. Let's get started! 🎯
Form Data refers to the information users enter in HTML forms. This data is sent to the server when the form is submitted. In this tutorial, we'll learn how to handle form data using Flask's built-in request.form object.
Form Data is crucial for interactivity in web applications. Users can input information, and the server processes it to perform desired actions. For example, registering a new user, updating a profile, or even searching for information.
Before we dive into the code, make sure you have Flask installed:
pip install flaskNow, let's create a new file named form_data.py.
Let's create a simple form that accepts a user's name and displays a greeting.
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
@app.route('/greet', methods=['POST'])
def greet():
name = request.form.get('name')
return f'Hello, {name}!'In the above code, we have created two routes: / and /greet. The home function renders a HTML template named home.html, which contains our form. The greet function handles the form submission and extracts the user's name from the form data.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form Data Example</title>
</head>
<body>
<h1>Enter your name</h1>
<form action="/greet" method="POST">
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<button type="submit">Submit</button>
</form>
</body>
</html>In the HTML template, we have a simple form that sends a POST request to the /greet route when submitted. The form data is sent as name in the request.
Run your application:
python form_data.pyNow, open your browser and navigate to http://localhost:5000. Enter a name and click Submit. You should see a greeting with the entered name!
flash() function to display error messages.Let's now create a form that accepts a file upload. We'll use the request.files object to handle the uploaded file.
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
@app.route('/upload', methods=['POST'])
def upload():
file = request.files['file']
if file.filename == '':
return "No selected file"
if file and file.filename.endswith('.txt'):
file.save(file.filename)
return f'File {file.filename} uploaded successfully!'
else:
return "Invalid file type. Only .txt files are allowed."<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Upload Example</title>
</head>
<body>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
<h1>Upload a text file</h1>
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">Upload</button>
</form>
</body>
</html>In this example, we've updated the form to accept file uploads. The form data is sent as file in the request. We check if the file is a .txt file and save it if it is.
Run your application:
python form_data.pyNow, open your browser and navigate to http://localhost:5000. Upload a text file and see the result!
That's it for today! We've covered the basics of handling form data using Flask's request.form object. In the next lesson, we'll dive deeper into handling complex forms and form validation. Until then, happy coding! 📝