Saturday, November 16, 2024
Google search engine
HomeLanguagesCreate Contact Us using WTForms in Flask

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:

  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:rahuls@gmail.com, 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:

RELATED ARTICLES

Most Popular

Recent Comments