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!
▶️ 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
When I submit the form I get the 404 error page
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?
aaaaahhh it's a hard framework to learn. Soooo many methods and references in there. But thank you anyways for every detail.
How can i find navbar.html?
finally after 5 videos someone that explains everything clearly!
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
SECRET KEY = "f off"
From all the deaf listeners / watchers
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?
This is one of those cases where youtube videos are more helpful documentation than the actual documentation. Dear oh dear.
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.
cant get bootstrap to reflect changes in name.html EX: {{ form.name.label( class = "form-label" ) }} doesnt change the look
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!
Amazing lecture sir… Please keep uploading new updated videos on flask. you sre the best mentor
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')
very good tutorial, thanks
Could anyone help me to hide the secret key using .gitignore , it happens somewhere around @ 6:00 in the video
excellent video, just subscribed!!!
I like you are smile everytime when you saying WTF
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.)?