Project Brief
Today’s task is to create a webpage that contains a survey people can fill in. This can be useful to get feedback from people on a certain topic. You can use any Python web framework. However, the code in the solution section uses Flask to build the webpage.
Expected Output
Here is how the webpage should look more or less:
When the user presses “Submit”, two things should happen. First, the browser should show a “Thank you” page:
Second, the program should add the user’s data in a row inside a CSV file inside the project. Here is what my CSV file will look like:
Environment Setup Instructions
Install the required libraries with:
pip install flask
Execute with python main.py and open
http://127.0.0.1:5000 in your browser to see the webpage.
Project Solution
Feel free to post your questions or comments in the comment section below.
Happy Coding!
Daily Python Projects Team
I’m learning Python and your page is getting me more excited about all the cool projects I’ll be able to build! Big fan!
Hi,
here is my main.py
from flask import Flask, render_template, request, redirect, url_for
import csv
app = Flask(__name__)
# Renders the survey from page
@app.route('/')
def home():
return render_template('survey.html')
# Handles the submission of the survey form.
# Saves the data to a CSV file and redirects to the thank you page.
@app.route('/submit', methods=['POST'])
def submit():
if request.method == 'POST':
name = request.form['name']
email = request.form['email']
feedback = request.form['feedback']
# Save the data to CSV file
with open('survey_results.csv', 'a', newline='') as csvfile:
fieldnames = ['Name', 'Email', 'Feedback']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
# Write header only if file is empty
if csvfile.tell() == 0:
writer.writeheader()
writer.writerow({'Name': name, 'Email': email, 'Feedback': feedback})
return redirect(url_for('thank_you'))
# Renders the thank you page after form submission.
@app.route('/thank_you')
def thank_you():
return render_template('thank_you.html')
if __name__ == "__main__":
app.run(debug=True)