Templates and Forms in Python Web Development
Learn how to create dynamic web pages with templates, handle form data, and process requests using Python frameworks like Flask or Django. …
Updated July 17, 2023
Learn how to create dynamic web pages with templates, handle form data, and process requests using Python frameworks like Flask or Django.
In the world of web development, creating interactive and engaging user experiences is crucial. One essential aspect of this is handling forms and template rendering. In this article, we’ll explore how templates and forms work in Python web development, focusing on the popular Flask framework.
Definition of Templates and Forms
Templates refer to reusable pieces of code that define the structure and layout of a web page. They’re used to render dynamic content based on data provided by the application or user input. On the other hand, forms are HTML elements used for collecting user input through various fields like text boxes, dropdown menus, checkboxes, etc.
Step-by-Step Explanation: Template Rendering with Flask
Let’s take a step-by-step approach to understanding template rendering using Flask:
Step 1: Install Flask
First, install the Flask framework using pip:
pip install flask
Step 2: Create Templates
Create a folder called templates
within your project directory. Inside this folder, create an HTML file named index.html
. This will serve as our template for rendering dynamic content.
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Template Rendering</title>
</head>
<body>
<h1>{{ title }}</h1>
<p>This is a dynamic web page!</p>
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
</body>
</html>
Step 3: Define Templates and Render Content
In your Flask application, import the render_template
function and define a template variable to store our template. Then, render the content using the defined template.
app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
title = 'Welcome!'
items = ['Item 1', 'Item 2', 'Item 3']
return render_template('index.html', title=title, items=items)
if __name__ == '__main__':
app.run(debug=True)
In this example, the render_template
function is used to render the content of the index.html
template. The title
and items
variables are passed as arguments to the template.
Step-by-Step Explanation: Form Handling with Flask
Now that we’ve covered template rendering, let’s explore form handling using Flask:
Step 1: Create a Form
Create an HTML file named form.html
within your templates
folder. This will serve as our form for collecting user input.
templates/form.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Handling</title>
</head>
<body>
<h1>Submit a form!</h1>
<form action="/submit" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>
Step 2: Handle Form Data
In your Flask application, define a route to handle form data. Use the request
object to access the form data.
app.py
from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('form.html')
@app.route('/submit', methods=['POST'])
def submit_form():
name = request.form.get('name')
email = request.form.get('email')
# Handle form data here
print(f"Name: {name}, Email: {email}")
return "Form submitted successfully!"
if __name__ == '__main__':
app.run(debug=True)
In this example, the /submit
route is used to handle form data. The request.form.get()
function is used to access the form data.
Conclusion
Templates and forms are essential components of web development. By understanding how to create templates and handle forms using Flask, you can build dynamic and interactive user experiences. Remember to use plain language, avoid jargon, and provide clear code snippets to make your content accessible to a wider audience.