pip install flask flask-wtf wtforms
Create a folder for your project and navigate to it:
mkdir flask_forms
cd flask_forms
Create a Python file app.py
and add the basic Flask setup:
from flask import Flask, render_template, request
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key'
if __name__ == "__main__":
app.run(debug=True)
The SECRET_KEY is required for CSRF protection when handling forms
Create a new file forms.py
and define a form using WTForms:
from flask_wtf import FlaskForm
from wtforms import StringField, EmailField, SubmitField
from wtforms.validators import DataRequired, Email
class ContactForm(FlaskForm):
name = StringField("Name", validators=[DataRequired()])
email = EmailField("Email", validators=[DataRequired(), Email()])
submit = SubmitField("Submit")
Inside the templates
folder, create form.html
:
<!DOCTYPE html>
<html>
<head>
<title>Flask Forms</title>
</head>
<body>
<h1>Contact Form</h1>
<form method="POST">
{{ form.hidden_tag() }}
<p>
{{ form.name.label }}<br>
{{ form.name(size=30) }}
</p>
<p>
{{ form.email.label }}<br>
{{ form.email(size=30) }}
</p>
<p>{{ form.submit() }}</p>
</form>
</body>
</html>
app.py
to Handle Form DataModify app.py
to import and use the form:
from flask import Flask, render_template, redirect, flash
from forms import ContactForm
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key'
@app.route("/contact", methods=["GET", "POST"])
def contact():
form = ContactForm()
if form.validate_on_submit():
name = form.name.data
email = form.email.data
flash(f"Form submitted successfully! Name: {name}, Email: {email}", "success")
return redirect("/contact")
return render_template("form.html", form=form)
if __name__ == "__main__":
app.run(debug=True)
Modify form.html
to display flash messages:
{% with messages = get_flashed_messages(with_categories=True) %}
{% if messages %}
{% for category, message in messages %}
<p style="color: green;">{{ message }}</p>
{% endfor %}
{% endif %}
{% endwith %}
To improve form styling, include Bootstrap in form.html
:
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
</head>
Modify the form to use Bootstrap classes:
<form method="POST" class="container mt-4">
{{ form.hidden_tag() }}
<div class="mb-3">
{{ form.name.label(class="form-label") }}
{{ form.name(class="form-control") }}
</div>
<div class="mb-3">
{{ form.email.label(class="form-label") }}
{{ form.email(class="form-control") }}
</div>
<button type="submit" class="btn btn-primary">{{ form.submit.label }}</button>
</form>
In this guide, you have learned how to:
✅ Set up Flask and Flask-WTF
✅ Create a form using WTForms
✅ Render and validate forms in Flask
✅ Handle form submissions and display flash messages
✅ Improve UI with Bootstrap
Now, you can build secure and interactive forms in your Flask applications! 🚀