Contact forms are an essential component of many websites, allowing visitors to get in touch with website owners, provide feedback, or request information. Creating a contact form in Python can be a straightforward process with the right tools and libraries. In this article, we will walk you through the steps to create a basic contact form using Python and the Flask web framework.
Prerequisites
Before we begin, make sure you have the following prerequisites installed:
- Python: You’ll need Python installed on your system. You can download it from the official website at python.org.
- Flask: Flask is a lightweight Python web framework. You can install it using pip:
pip install Flask
3. A text editor or integrated development environment (IDE) for writing Python code. Popular choices include Visual Studio Code, PyCharm, or Sublime Text.
Setting Up the Project
- Create a project directory where you will store your code and files for the contact form.
- Inside your project directory, create a Python file, e.g.,
app.py, which will contain the code for your contact form. - Create a folder named
templatesinside your project directory. This is where you’ll store your HTML templates. - Inside the
templatesfolder, create an HTML file namedcontact.html. This file will define the structure of your contact form.
Building the Contact Form
HTML Structure (contact.html)
<!DOCTYPE html>
<html>
<head>
<title>Contact Us</title>
</head>
<body>
<h1>Contact Us</h1>
<form action="/submit" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<label for="message">Message:</label><br>
<textarea id="message" name="message" rows="5" required></textarea><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Python Code (app.py)
pythonCopy code
from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
# Route to display the contact form
@app.route('/')
def contact():
return render_template('contact.html')
# Route to handle form submission
@app.route('/submit', methods=['POST'])
def submit():
if request.method == 'POST':
name = request.form['name']
email = request.form['email']
message = request.form['message']
# You can perform actions with the form data here, like sending emails or saving it to a database.
return f"Thank you, {name}! Your message has been sent successfully."
if __name__ == '__main__':
app.run(debug=True)
Explanation
- We create a basic HTML structure for the contact form in
contact.html. This form includes fields for the user’s name, email address, and message, along with a submit button. - In
app.py, we import the necessary Flask modules and create a Flask application instance. - We define two routes using the
@app.routedecorator. The/route displays the contact form, while the/submitroute handles form submissions. - In the
contactfunction, we userender_templateto render thecontact.htmltemplate when a user visits the root URL/. - In the
submitfunction, we check if the HTTP method isPOST. If it is, we retrieve the form data usingrequest.formand can perform actions with it, such as sending an email or saving it to a database. In this example, we return a simple confirmation message. - Finally, we run the Flask app with
app.run(debug=True).
Running the Contact Form
- Create a project directory where you will store your code and files for the contact form.
- Inside your project directory, create a Python file, e.g.,
app.py, which will contain the code for your contact form. - Create a folder named
templatesinside your project directory. This is where you’ll store your HTML templates. - Inside the
templatesfolder, create an HTML file namedcontact.html. This file will define the structure of your contact form.
Building the Contact Form
HTML Structure (contact.html)
<!DOCTYPE html>
<html>
<head>
<title>Contact Us</title>
</head>
<body>
<h1>Contact Us</h1>
<form action="/submit" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<label for="message">Message:</label><br>
<textarea id="message" name="message" rows="5" required></textarea><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Python Code (app.py)
from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
# Route to display the contact form
@app.route('/')
def contact():
return render_template('contact.html')
# Route to handle form submission
@app.route('/submit', methods=['POST'])
def submit():
if request.method == 'POST':
name = request.form['name']
email = request.form['email']
message = request.form['message']
# You can perform actions with the form data here, like sending emails or saving it to a database.
return f"Thank you, {name}! Your message has been sent successfully."
if __name__ == '__main__':
app.run(debug=True)
Explanation
- We create a basic HTML structure for the contact form in
contact.html. This form includes fields for the user’s name, email address, and message, along with a submit button. - In
app.py, we import the necessary Flask modules and create a Flask application instance. - We define two routes using the
@app.routedecorator. The/route displays the contact form, while the/submitroute handles form submissions. - In the
contactfunction, we userender_templateto render thecontact.htmltemplate when a user visits the root URL/. - In the
submitfunction, we check if the HTTP method isPOST. If it is, we retrieve the form data usingrequest.formand can perform actions with it, such as sending an email or saving it to a database. In this example, we return a simple confirmation message. - Finally, we run the Flask app with
app.run(debug=True).
Running the Contact Form
To run your contact form, open a terminal, navigate to your project directory, and run the following command:
python app.py
This will start your Flask application. You can access your contact form by opening a web browser and navigating to http://localhost:5000.
You’ve now successfully created a basic contact form in Python using Flask! You can further enhance your contact form by adding validation, handling file uploads, and integrating it with a backend database or email service to store and manage user submissions.