Seriously, WTF FLASK? Today I face my greatest challenge in using Flask — WTForms. In this article, I would like to share about my learning experience using Flask and the learning process of creating a form with Flask-WTForms.

Creating forms with Flask-WTForms

1 — (.py file) I need to import the following classes from flask_wtf and wtforms. A FlaskForm is a secure form with cross-site request forgery (csrf) protection, whihc means that token will not be leaked in the server logs. StringField is the base for most of the more complicated fields, and represents <input type=“text”>.

2 — (.py file) Create an app.secret_key. This secret key can be any string, as long as it is a secret only to you.

3 — (.py file) Create a Form Child Class with the FlaskForm Parent Class, giving it the variables you want it to have. This creates two variables with the <input type=“text”> properties to be passed into the HTML file later on.

4 — (.py file) Instantiate that class and create an object, to be passed into the ‘login.html’ file.

5 — (.html file) {{form.csrf_token}} is necessary to ensure that our form is CSRF protected.

Validation with Flask-WTForms

1 — (.py file)Import DataRequired class from wtf.validators.

2 — (.py file)Add validators to the variables that I want to be validated. When a form is submitted, the errors will be submitted in the form of a list, in this format:


3 —(.py file) Add validators to the variables that I want to be validated.It must be able to respond to POST requests as well.

4 —(.html file) Use Python code to catch errors. For each error, it will be displayed in red.

5 —(.html file) Add novalidate to remove browser validation.

Well, that is my sharing for today. I hope this sharing helped y’all understand what I learnt about Flask and I will definitely be back with more sharings to talk about my learning journey in code.

Jing Kai



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store