Create Contact Us using WTForms inn Flask
0 593
Introduction
Building a "Contact Us" form is a common feature in many web applications. With Flask and WTForms, you can create a secure and elegant contact form quickly. In this article, we'll set up a fully validated contact form using WTForms in Flask.
Project Structure
Define a clean project layout:
app.py– main Flask applicationforms.py– WTForms definitionstemplates/– HTML templates
Installing Dependencies
Make sure you have Flask and Flask-WTF installed. You can install them using pip:
pip install Flask Flask-WTF
Defining the Contact Form
Create forms.py and define the fields and validation:
from flask_wtf import FlaskForm
from wtforms import StringField, TextAreaField, SubmitField
from wtforms.validators import DataRequired, Email, Length
class ContactForm(FlaskForm):
name = StringField('Name', validators=[DataRequired(), Length(min=2, max=50)])
email = StringField('Email', validators=[DataRequired(), Email(), Length(max=120)])
message = TextAreaField('Message', validators=[DataRequired(), Length(min=10, max=500)])
submit = SubmitField('Send Message')
Setting Up the Flask App
In app.py, configure and use the form:
from flask import Flask, render_template, flash, redirect, url_for
from forms import ContactForm
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key_here'
@app.route('/contact', methods=['GET', 'POST'])
def contact():
form = ContactForm()
if form.validate_on_submit():
# Process or store form data
flash('Thank you for contacting us!', 'success')
return redirect(url_for('contact'))
return render_template('contact.html', form=form)
if __name__ == '__main__':
app.run(debug=True)
Creating the HTML Template
Build templates/contact.html to render the form and show messages:
<!-- templates/contact.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact Us</title>
</head>
<body>
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
<ul>
{% for category, message in messages %}
<li class="{{ category }}">{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
<h1>Contact Us</h1>
<form method="POST">
{{ form.hidden_tag() }}
<p>
{{ form.name.label }}<br>
{{ form.name(size=40) }}<br>
{% for error in form.name.errors %}
<span class="error">{{ error }}</span>
{% endfor %}
</p>
<p>
{{ form.email.label }}<br>
{{ form.email(size=40) }}<br>
{% for error in form.email.errors %}
<span class="error">{{ error }}</span>
{% endfor %}
</p>
<p>
{{ form.message.label }}<br>
{{ form.message(rows=5, cols=40) }}<br>
{% for error in form.message.errors %}
<span class="error">{{ error }}</span>
{% endfor %}
</p>
<p>{{ form.submit() }}</p>
</form>
</body>
</html>
Key Considerations
- Always include
SECRET_KEYto protect the form against CSRF. - Use WTForms validators to check input completeness and format.
- Show validation feedback directly under fields for better UX.
- Flash a confirmation message after successful submission.
Conclusion
Creating a "Contact Us" form with WTForms in Flask simplifies form handling, validation, and user feedback. Following this setup ensures that your form is both user-friendly and secure, ready for production-level use.
If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!
Share:



Comments
Waiting for your comments