Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Flask Templates
  • Jinja2
  • Flask-REST API
  • Python SQLAlchemy
  • Flask Bcrypt
  • Flask Cookies
  • Json
  • Postman
  • Django
  • Flask Projects
  • Flask Interview Questions
  • MongoDB
  • Python MongoDB
  • Python Database
  • ReactJs
  • Vue.Js
Open In App
Next Article:
Sending Emails Using API in Flask-Mail
Next article icon

Create Contact Us using WTForms in Flask

Last Updated : 26 May, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

WTForms is a library designed to make the processing of forms easier to manage. It handles the data submitted by the browser very easily. In this article, we will discuss how to create a contact us form using WTForms.

Advantages of WT-FORM:

  1. We don’t have to worry about validators.
  2. Avoidance of Cross-Site Request Forgery (CSRF).
  3. WTForms come as classes, so all the good come’s from an object form.
  4. No need to create any <label> or <input> elements manually using HTML.

Installation

Use the Terminal to install Flask-WTF.

pip install Flask-WTF

Stepwise Implementation

Step 1: Create a class having all elements that you want in your Form in the main.py.

Python3

from flask_wtf import FlaskForm
from wtforms import StringField, validators, PasswordField, SubmitField
from wtforms.validators import DataRequired, Email
import email_validator
  
  
class contactForm(FlaskForm):
    name = StringField(label='Name', validators=[DataRequired()])
    email = StringField(label='Email', validators=[
      DataRequired(), Email(granular_message=True)])
       message= StringField(label='Message')
    submit = SubmitField(label="Log In")
                      
                       

Step 2: Create the object of the form and pass the object as a parameter in the render_template

Python3

@app.route("/", methods=["GET", "POST"])
def home():
    cform = contactForm()
    return render_template("contact.html", form=cform)
                      
                       

Step 3: Add CSRF protection. Add a secret key.

app.secret_key = "any-string-you-want-just-keep-it-secret"

Step 4: Add the fields in the contact.html HTML FILE.

{{ form.csrf_token }} is used to provide csrf protection.

HTML

<!DOCTYPE HTML>
  
<html>
    <head>
        <title>Contact</title>
    </head>
    <body>
        <div class="container">
            <h1>Contact Us</h1>
            <form method="POST" action="{{ url_for('home') }}">
                {{ form.csrf_token }}
                  
                <p>
                    {{ form.name.label }} 
                    <br>
                    {{ form.name }}
                </p>
  
  
                  
                <p>
                    {{ form.email.label }} 
                    <br>
                    {{ form.email(size=30) }}
                </p>
  
  
                  
                <p>
                    {{ form.message.label }} 
                    <br>
                    {{ form.message }}
                </p>
  
                {{ form.submit }}
            </form>
        </div>
    </body>
</html>
                      
                       

Step 5: Validating the Form and receiving the data.

Python3

@app.route("/", methods=["GET", "POST"])
def home():
    cform = contactForm()
    if cform.validate_on_submit():
        print(f"Name:{cform.name.data}, 
              E-mail:{cform.email.data}, 
              message:{cform.message.data}")
    else:
        print("Invalid Credentials")
                
    return render_template("contact.html", form=cform)
                      
                       

Complete Code:

Python3

from flask import Flask, render_template, request, redirect, url_for
from flask_wtf import FlaskForm
from wtforms import StringField, validators, PasswordField, SubmitField
from wtforms.validators import DataRequired, Email
import email_validator
  
app = Flask(__name__)
app.secret_key = "any-string-you-want-just-keep-it-secret"
  
class contactForm(FlaskForm):
    name = StringField(label='Name', validators=[DataRequired()])
    email = StringField(
      label='Email', validators=[DataRequired(), Email(granular_message=True)])
    message = StringField(label='Message')
    submit = SubmitField(label="Log In")
  
  
@app.route("/", methods=["GET", "POST"])
def home():
    cform=contactForm()
    if cform.validate_on_submit():
            print(f"Name:{cform.name.data}, E-mail:{cform.email.data},
                  message:{cform.message.data}")
    return render_template("contact.html",form=cform)
  
  
if __name__ == '__main__':
    app.run(debug=True)
                      
                       

Output:

Name:Rahul Singh, E-mail:[email protected], message:This is Sample gfg Output!!!

Adding Bootstrap

We can also add the bootstrap to the above form to make it look interactive. For this, we will use the Flask-Bootstrap library. To install this module type the below command in the terminal.

pip install Flask-Bootstrap

Step 1: Create base.html

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
    {% block content %}{% endblock %}
</body>
</html>
                      
                       

Step 2: Modify contact.html to

with single line {{ wtf.quick_form(form) }}

HTML

{% extends 'bootstrap/base.html' %}
{% import "bootstrap/wtf.html" as wtf %}
  
{% block title %}
Contact Us
{% endblock %}
  
{% block content %}
        <div class="container">
            <h1>Contact Us</h1>
            {{ wtf.quick_form(form) }}
        </div>
{% endblock %}l>
                      
                       

Step 3: MODIFY main.py

It is very simple to modify the .py file. We just have to import the module and add the below line into the code

Bootstrap(app)

Python3

from flask import Flask, render_template, request, redirect, url_for
from flask_wtf import FlaskForm
from wtforms import StringField, validators, PasswordField, SubmitField
from wtforms.validators import DataRequired, Email
from flask_bootstrap import Bootstrap
import email_validator
app = Flask(__name__)
Bootstrap(app)
app.secret_key = "any-string-you-want-just-keep-it-secret"
  
class contactForm(FlaskForm):
    name = StringField(label='Name', validators=[DataRequired()])
    email = StringField(label='Email', validators=[DataRequired(), Email(granular_message=True)])
    message = StringField(label='Message')
    submit = SubmitField(label="Log In")
  
  
@app.route("/", methods=["GET", "POST"])
def home():
    cform=contactForm()
    if cform.validate_on_submit():
            print(f"Name:{cform.name.data}, E-mail:{cform.email.data}, message:{cform.message.data}")
    return render_template("contact.html",form=cform)
  
  
if __name__ == '__main__':
    app.run(debug=True)
                      
                       

Output:



Next Article
Sending Emails Using API in Flask-Mail

R

rajasethi056
Improve
Article Tags :
  • Python
  • Web Technologies
  • Flask Projects
  • Python Flask
Practice Tags :
  • python

Similar Reads

  • Flask Tutorial
    Flask is a lightweight and powerful web framework for Python. It’s often called a "micro-framework" because it provides the essentials for web development without unnecessary complexity. Unlike Django, which comes with built-in features like authentication and an admin panel, Flask keeps things mini
    9 min read
  • Flask Setup & Installation

    • Introduction to Web development using Flask
      Flask is a lightweight and flexible web framework for Python. It's designed to make getting started with web development quick and easy, while still being powerful enough to build complex web applications. It is an API of Python that allows us to build web applications. It was developed by Armin Ron
      11 min read

    • Differences Between Django vs Flask
      Django and Flask are two of the most popular web frameworks for Python. Flask showed up as an alternative to Django, as designers needed to have more flexibility that would permit them to decide how they want to implement things, while on the other hand, Django does not permit the alteration of thei
      8 min read

    • How to Install Flask in Windows?
      Flask is basically a Python module. It can work with Python only and it is a web-developing framework. It is a collection of libraries and modules. Frameworks are used for developing web platforms. Flask is such a type of web application framework. It is completely written in Python language. Unlike
      2 min read

    Flask Quick Start

    • Flask - (Creating first simple application)
      Building a webpage using python.There are many modules or frameworks which allow building your webpage using python like a bottle, Django, Flask, etc. But the real popular ones are Flask and Django. Django is easy to use as compared to Flask but Flask provides you with the versatility to program wit
      6 min read

    • How to Run a Flask Application
      After successfully creating a Flask app, we can run it on the development server using the Flask CLI or by running the Python script. Simply execute one of the following commands in the terminal: flask --app app_name runpython app_nameFile StructureHere, we are using the following folder and file. D
      4 min read

    • Flask App Routing
      App Routing means mapping the URLs to a specific function that will handle the logic for that URL. Modern web frameworks use more meaningful URLs to help users remember the URLs and make navigation simpler.  Example: In our application, the URL ("/") is associated with the root URL. So if our site's
      3 min read

    • Flask - HTTP Method
      In this article, we will learn how to handle HTTP methods, such as GET and POST in Flask using Python. Before starting let's understand the basic terminologies: GET: to request data from the server.POST: to submit data to be processed to the server.PUT: replaces the entire resource with new data. If
      5 min read

    • Flask - Variable Rule
      Flask variable rules allow us to create dynamic URLs by defining variable parts within the route. This makes it possible to capture values from the URL and pass them to view functions. Variable RulesA variable rule is defined using <variable-name> within the route.The captured variable is auto
      3 min read

    • Redirecting to URL in Flask
      Flask is a backend server that is built entirely using Python. It is a  framework that consists of Python packages and modules. It is lightweight which makes developing backend applications quicker with its features. In this article, we will learn to redirect a URL in the Flask web application. Redi
      3 min read

    • Python Flask - Redirect and Errors
      We'll discuss redirects and errors with Python Flask in this article. A redirect is used in the Flask class to send the user to a particular URL with the status code. conversely, this status code additionally identifies the issue. When we access a website, our browser sends a request to the server,
      4 min read

    • How to Change Port in Flask app
      In this article, we will learn to change the port of a Flask application. The default port for the Flask application is 5000. So we can access our application at the below URL. http://127.0.0.1:5000/ We may want to change the port may be because the default port is already occupied. To do that we ju
      1 min read

    • Changing Host IP Address in Flask
      By default, Flask runs on 127.0.0.1:5000, which means it can only be accessed from the same machine. However, we may want to access our Flask app from other devices on the same network or even from the internet. To do this, we need to change the host IP address. Changing the IP address in a Flask ap
      2 min read

    Serve Templates and Static Files in Flask

    • Flask Rendering Templates
      Flask is a lightweight Python web framework that enables developers to build web applications easily. One of its key features is template rendering, which allows dynamic content generation using Jinja2 templating. In this guide, we'll explore how to render templates in Flask. Setting up FlaskSetting
      7 min read

    • CSRF Protection in Flask
      Cross-Site Request Forgery (CSRF) is a security vulnerability where an attacker tricks a user into unknowingly submitting a request to a web application in which they are authenticated. This can lead to unauthorized actions being performed on behalf of the user, such as changing account settings or
      3 min read

    • Template Inheritance in Flask
      Template inheritance is a powerful feature in Jinja, the templating engine used in Flask. It allows us to define a common structure for web pages, such as headers, footers, and navigation bars, in a base template. This prevents redundant code and makes managing multiple pages easier. Prerequisite -
      2 min read

    • Placeholders in jinja2 Template - Python
      Web pages use HTML for the things that users see or interact with. But how do we show things from an external source or a controlling programming language like Python? To achieve this templating engine like Jinja2 is used. Jinja2 is a templating engine in which placeholders in the template allow wri
      5 min read

    • How to serve static files in Flask
      In Flask, static files refer to files such as CSS, JavaScript, images, videos, and audio files that do not change dynamically. Flask provides a built-in way to serve these static files using the /static directory. This guide will show how to serve different types of static files in a Flask web appli
      4 min read

    • Uploading and Downloading Files in Flask
      This article will go over how to upload and download files using a Flask database using Python. Basically, we have a section for uploading files where we can upload files that will automatically save in our database. When we upload a file and submit it, a message stating that your file has been uplo
      7 min read

    • How to Upload File in Python-Flask
      File uploading is a typical task in web apps. Taking care of file upload in Flask is simple all we need is to have an HTML form with the encryption set to multipart/form information to publish the file into the URL. The server-side flask script brings the file from the request object utilizing the r
      2 min read

    • Upload Multiple files with Flask
      In online apps, uploading files is a common task. Simple HTML forms with encryption set to multipart/form information are all that is required to publish a file into a URL when using Flask for file upload. The file is obtained from the request object by the server-side flask script using the request
      2 min read

    • Flask - Message Flashing
      In this article, we will discuss Flask - Message Flashing. As we know best Graphical User Interface provides feedback to a user when users interact, as an example, we know that desktop applications use the messages box or JS for an alert purpose. generating like same informative message is easy to d
      6 min read

    • Create Contact Us using WTForms in Flask
      WTForms is a library designed to make the processing of forms easier to manage. It handles the data submitted by the browser very easily. In this article, we will discuss how to create a contact us form using WTForms. Advantages of WT-FORM:We don't have to worry about validators.Avoidance of Cross-S
      3 min read

    • Sending Emails Using API in Flask-Mail
      Python, being a powerful language don’t need any external library to import and offers a native library to send emails- “SMTP lib”. “smtplib” creates a Simple Mail Transfer Protocol client session object which is used to send emails to any valid email id on the internet. This article revolves around
      3 min read

    User Registration, Login, and Logout in Flask

    • How to Add Authentication to App with Flask-Login
      We can implement authentication, login/logout functionality in flask app using Flask-Login. In this article, we'll explore how to add authentication to a Flask app using Flask-Login. To get started, install Flask, Flask-Login, Flask-SQLAlchemy and Werkzeug using this command: pip install flask flask
      6 min read

    • Add User and Display Current Username in Flask
      This article covers adding users and displaying their usernames in Flask. After login, users are redirected to a profile page with a welcome message. User data is stored in MySQL for easy management via phpMyAdmin. Creating Templates for User InterfaceWe need three HTML files inside a templates fold
      8 min read

    • Password Hashing with Bcrypt in Flask
      In this article, we will use Password Hashing with Bcrypt in Flask using Python. Password hashing is the process of converting a plaintext password into a hashed or encrypted format that cannot be easily reverse-engineered to reveal the original password. Bcrypt is a popular hashing algorithm used t
      2 min read

    • How to Store Username and Password in Flask
      This article covers storing usernames and passwords in a Flask web app using MySQL. After logging in, users see a welcome message with their username. InstallationTo make our project we first create a virtual environment, to learn how to create and activate a virtual environment, refer to - Python v
      6 min read

    • Flask - Role Based Access Control
      Role-Based Access Control (RBAC) is a security mechanism that restricts user access based on their roles within an application. Instead of assigning permissions to individual users, RBAC groups users into roles and each role has specific permissions. For example, in a Flask app, we might have roles
      10 min read

    • How to use Flask-Session in Python Flask
      Sessions in Flask store user-specific data across requests, like login status, using cookies. Data is stored on the client side but signed with a secret key to ensure security. They help maintain user sessions without requiring constant authentication. This article demonstrates how to implement serv
      4 min read

    • Flask Cookies
      Cookies store user data in the browser as key-value pairs, allowing websites to remember logins, preferences, and other details. This helps improve the user experience by making the site more convenient and personalized. Make sure that flask is already installed on our system - Flask Installation Se
      4 min read

    • How to return a JSON response from a Flask API ?
      Flask is one of the most widely used python micro-frameworks to design a REST API. In this article, we are going to learn how to create a simple REST API that returns a simple JSON object, with the help of a flask. Prerequisites: Introduction to REST API What is a REST API? REST stands for Represent
      3 min read

    Define and Access the Database in Flask

    • Flask SQLAlchemy Tutorial for Database
      Flask doesn’t have a built-in way to handle databases, so it relies on SQLAlchemy, a powerful library that makes working with databases easier. SQLAlchemy provides an Object Relational Mapper (ORM), allowing developers to interact with databases using Python code instead of raw SQL. This brings seve
      8 min read

    • How to Build a Web App using Flask and SQLite in Python
      Flask is a lightweight Python web framework with minimal dependencies. It lets you build applications using Python libraries as needed. In this article, we'll create a Flask app that takes user input through a form and displays it on another page using SQLite. Run the following commands to install F
      3 min read

    • Sending Data from a Flask app to MongoDB Database
      This article covers how we can configure a MongoDB database with a Flask app and store some data in the database after configuring it. Before directly moving to the configuration phase here is a short overview of all tools and software we will use. MongoDB is an open-source database that stores data
      5 min read

    • Making a Flask app using a PostgreSQL database
      The Postgres database can be accessed via one of two methods in Python. Installing PgAdmin4 is the first step because it offers a user interface for interacting with databases and another for using the psycopg2 connector. In this post, we'll concentrate on a different approach that lets us alter the
      4 min read

    • Login and Registration Project in Flask using MySQL
      Creating a user authentication system is a fundamental part of web applications. This guide will help you build a Login and Registration system using Flask and MySQL. Prerequisites - Basic knowledge of Python, MySQL Workbench, and Flask. To learn how to build login and registration in Flask, let's c
      6 min read

    • How to Execute Raw SQL in Flask - SQLAlchemy App
      In a Flask application that uses SQLAlchemy, we usually interact with the database using Python objects and methods. However, there are times when we need to execute raw SQL queries directly—for example, to optimize performance, run complex queries, or perform database-specific operations. This guid
      5 min read

    Flask Deployment and Error Handling

    • Subdomain in Flask | Python
      Prerequisite: Introduction to Flask In this article, we will learn how to setup subdomains in Flask. But first, let's go through the basic like what is DNS and subdomains. Domain Name System (DNS): The Domain Name System (DNS) is a hierarchical and decentralized naming system for computers, services
      3 min read

    • Handling 404 Error in Flask
      A 404 Error occurs when a page is not found. This can happen due to several reasons: The URL was changed, but the old links were not updated.The page was deleted from the website.The user mistyped the URL.To improve user experience, websites should have a custom error page instead of showing a gener
      3 min read

    • Deploy Python Flask App on Heroku
      Flask is a web application framework written in Python. Flask is based on the Werkzeug WSGI toolkit and Jinja2 template engine. Both are Pocco projects. This article revolves around how to deploy a flask app on Heroku. To demonstrate this, we are first going to create a sample application for a bett
      2 min read

    • Deploy Machine Learning Model using Flask
      In this article, we will build and deploy a Machine Learning model using Flask. We will train a Decision Tree Classifier on the Adult Income Dataset, preprocess the data, and evaluate model accuracy. After training, we’ll save the model and create a Flask web application where users can input data a
      8 min read

  • Python Flask Projects with Source Code (Beginners to Advanced)
    Flask, a Python web application framework, was created by Armin Ronacher. Known for its lightweight and efficient nature, Flask is designed for quick starts and accommodates complex applications. It is based on the Werkzeug WSGI toolkit and Jinja2 template engine. In this article, we’ve curated a li
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences