Flask Fridays #5: Unleash the Power of Web Forms with WTF!

Posted by


Welcome to Flask Fridays #5! In this tutorial, we will be focusing on web forms with WTF (WTForms) in Flask. WTF is a lightweight form validation and rendering library for Python web development with Flask. It helps us handle form input effortlessly and securely.

To start off, make sure you have Flask installed in your virtual environment. If you haven’t set up a virtual environment yet, you can do so by running the following commands:

pip install virtualenv
virtualenv venv
source venv/bin/activate

Next, install Flask in the virtual environment:

pip install Flask

Now that you have Flask installed, let’s create a new Flask app. Create a new directory for your Flask app and navigate to it in the terminal. Inside the directory, create a new Python file, for example app.py.

In app.py, import the necessary modules:

from flask import Flask, render_template, request
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired

Next, create a Flask app and configure a secret key for CSRF protection:

app = Flask(__name__)
app.config['SECRET_KEY'] = 'supersecretkey'

Now, let’s create a simple form using WTF. Define a class for the form with the fields you want to include:

class MyForm(FlaskForm):
    name = StringField('Name', validators=[DataRequired()])
    submit = SubmitField('Submit')

In the form class, we defined a StringField for the name field and a SubmitField for the submit button.

Next, create a route in your Flask app to render the form and handle form submission:

@app.route('/', methods=['GET', 'POST'])
def index():
    form = MyForm()
    if form.validate_on_submit():
        name = form.name.data
        return f'Hello, {name}!'
    return render_template('index.html', form=form)

In the route function, we instantiate the form class and check if the form has been submitted and is valid. If it is valid, we retrieve the data from the form and display a greeting message. If not, we render the form template with the form object.

Now, create a new directory in your app directory called templates. Inside the templates directory, create a new HTML file called index.html and add the following code:

<!DOCTYPE html>
<html>
<head>
    <title>Web Form with WTF</title>
</head>
<body>
    <h1>Submit your name</h1>
    <form method="POST">
        {{ form.hidden_tag() }}
        {{ form.name.label }}<br>
        {{ form.name(size=20) }}<br>
        {{ form.submit() }}
    </form>
</body>
</html>

In the HTML file, we have a simple form that includes the name field and a submit button. We use template tags to render the form fields from the Flask form.

To run your Flask app, add the following code at the bottom of your app.py file:

if __name__ == '__main__':
    app.run(debug=True)

Now, you can run your Flask app by executing python app.py in the terminal. Visit http://127.0.0.1:5000/ in your browser to see the form rendered. Enter your name and submit the form to see the greeting message.

Congratulations! You have successfully implemented web forms with WTF in Flask. You can customize the form fields, validators, and rendering as needed for your web application. Stay tuned for more Flask Fridays tutorials!

0 0 votes
Article Rating
43 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@Codemycom
1 month ago

▶️ Watch Entire Flask Friday Playlist ✅ Subscribe To My YouTube Channel:
https://bit.ly/3ig2eJn http://bit.ly/2IGzvOR
▶️ See More At: ✅ Join My Facebook Group:
https://Codemy.com http://bit.ly/2GFmOBz
▶️ Learn to Code at https://Codemy.com ✅ Buy a Codemy T-Shirt!
Take $30 off with coupon code: youtube1 http://bit.ly/2VC9WUN
▶️ Get The Code
http://bit.ly/2L1jBl5

@orick08
1 month ago

When I submit the form I get the 404 error page

@thomasyusuf1366
1 month ago

Ran my code same as yours and around 12:10 got this "TypeError: FlaskForm.validate_on_submit() missing 1 required positional argument: 'self' " any help?

@BenMrMakinesiyim
1 month ago

aaaaahhh it's a hard framework to learn. Soooo many methods and references in there. But thank you anyways for every detail.

@MaximusPrima
1 month ago

How can i find navbar.html?

@imnotaburrito9365
1 month ago

finally after 5 videos someone that explains everything clearly!

@wirrexx
1 month ago

Love what you are doing. However, I got an error pip install flask-wtf on windows. as It continue to say that the module is missing. However, I can see it in my requirements on pip freeze. Confusing

@oleksandrshuhurov7536
1 month ago

SECRET KEY = "f off"
From all the deaf listeners / watchers

@likbezlik
1 month ago

I looked at many Flask tutorials and yours is the only one that helped me find a solution to this simple form. Took me a few hours to fix some bugs though.

I was very confused with the attributes that we have to pass to the render_template "name=name" and "form=form". What exactly does this part do in the code?

@expressionamidstcacophony390
1 month ago

This is one of those cases where youtube videos are more helpful documentation than the actual documentation. Dear oh dear.

@pmatoss
1 month ago

I have no words to describe my gratitude for this series of videos. In addition to being extremely educational and educational, they are so realistic that I am applying them to an educational project that I am developing with a group of friends. Thank you very much for the great work. Greetings from Brazil.

@stephontidd7051
1 month ago

cant get bootstrap to reflect changes in name.html EX: {{ form.name.label( class = "form-label" ) }} doesnt change the look

@tradingoptions
1 month ago

2023: [Bug Fix] You need to add {{ form.csrf_token }} before or after this line {{ form.hidden_tag() }} on the name.html page. Else if form.validate_on_submit() == False

This is a great series of videos. Thanks!

@mehboob_pythonist
1 month ago

Amazing lecture sir… Please keep uploading new updated videos on flask. you sre the best mentor

@salmantas2335
1 month ago

in case of is there any one wondering how to change button text other than submit: just pass what you want into the SubmitField that you created in your class. for example: submit = SubmitField('sometext')

@GIULI4994
1 month ago

very good tutorial, thanks

@aditya.21
1 month ago

Could anyone help me to hide the secret key using .gitignore , it happens somewhere around @ 6:00 in the video

@david2358
1 month ago

excellent video, just subscribed!!!

@nerminqulu
1 month ago

I like you are smile everytime when you saying WTF

@Darkev77
1 month ago

As usual, clear and concise. Anyone know why I should use wtforms over typical html input tags with specified types (email, password, etc.) and properties (required, title, etc.)?