Flask for dummies Part 3 - Secured Forms, Flask Database

Hello there, welcome to the 3rd and final part of our flask for dummies blog series. Let's get started.


In this article, we'll learn

  • How to create secured forms.
  • Database connection using flask.
  • Conclusion.
If you aren't sure about the basics of creating flask and form handling using flask, do check our previous parts of this blog series.

Secured forms - WTForms:

Yes, you read it right, WTForms. It is a form validation library for python web development. This library helps us to overcome CSRF attacks (Cross-Site Request Forgery attacks) which forces the authenticated user to submit a form that might cause problems to the navigation of the pages and affect the backend as well. This also supports data validations. 

Let us go with an example to make the concept clear. 


First, install the library for WTForms using the command pip install Flask-WTF. Then create a new file as forms.py (You can give any name for this file. For better understanding, I've named it as forms.py)

Now import the flask_wtf library into your forms file.

Create a class named signup, and declare the attributes of the class. The attributes of this class are the input fields, text boxes, radio boxes, buttons that are needed in an HTML form.

In lines 6 and 7: I've created a Stringfield (Text box) and a button field. This attribute helps me to create a text field and a button field on an HTML page.

There are so many options like file field and radio button field which can be used in your HTML file.

You can also notice that there is a validator parameter where the DataRequired function is enclosed inside a list. This validator variable expects a list of validations that are needed for your form. 

All the different input fields and validator functions are clearly specified in the WTForms official documentations.

In line 9: A function def isvalid() is created which validates the input field since this WTForms supports form validation on the server-side as well. Here the input field is checked if the length of the string is greater than 4. We can include some complex validations as well. 


Now let us jump to the main flask file (main.py). A simple login form is created (Without using a password). Import the flask library and the forms.py file which was created now. 

In line 4: The secret key needs to be specified which is important for using WTForms. 

A login function is created which takes care of the login part. 

In line 9: An object is created for the signup class which is created in the forms.py

validate_on_submit() function checks if the button is clicked by the user.

In line 11: isvalid() function of the signup class which was manually created for form validation is called which checks the length of the username. 

In lines 12-14: The redirection of the HTML page is made(home.html, login.html) accordingly along with the form object which was created in line 9. 

(Do check out the previous blog if you aren't clear with redirect() function or render_template() functions of the flask)



We've used the same HTML code from the previous blog part with some minor changes. 

The form object from the main.py is passed to the login.html file which is accessed in lines 15, 16, and 17 of the login.html file. 

The csrf_token attribute of the form object ensures protection against CSRF attacks in a web application. 

The fields of the forms are accessed using the field name created in the forms.py file in the above-specified format (login.html). Class, id, placeholder, and other HTML attributes are specified as a parameter that can be used for styling and other purposes.

The username is displayed in the home.html file using Jinja Templating Language.


And there you go! We are done with creating a secured form using WTForms.

Let's have a look at flask databases.

Database connection - SQLAlchemy

Imagine yourself writing all the raw SQL queries while building a web app, which requires complex queries. Tedious isn't it?. SQLAlchemy provides the solution for this problem. Let's not waste our time, we'll jump into the code!

First, install the flask-SQLAlchemy library using the command, 

pip install flask-sqlalchemy

Let us clear the previous version of the main.py file and make a new one for the flask database


Now import the flask-sqlalchemy module in your main.py file as did in line 2. 

Create an "SQLALCHEMY_DATABASE_URI" variable for the database to be used. Here we've used SQLite database. You can use any database of your own choice.

Create a db object of class SQLALchemy and create another class of your own name which will be is the database table to be used. We've created a table with the table name as details. The attributes of the class are the columns of the database. Take a note of the constraints of the columns that are specified in the attributes. 

The __init__ function initializes the row of the database table. 

After successfully creating the database class, go to the terminal and do the following. 

First, enter python to execute python code in the terminal. Import the db object from the main.py file and execute the db.create_all() function which created the database table. 

Now that the database table is created successfully, let's have a look at inserting, viewing, and deleting a row.

In the log function, the response of the form is been checked and the action takes place accordingly. 

To add a row to the database table, the db.session.add(object) and db.session.commit() is executed. This piece of code creates a new row to the database table with values mentioned in the object. 

Lines 23, 24, and 25 clearly depict the procedure to create a row. 

To delete a row from the database table, the class_name.query.filter_by(column=value).delete() is used. This piece of code deletes the row from the database table with the specified filter. 

Line 27 in the main.py shows a sample of how to delete a row.  

Similarly class_name.query.all() function is used to select all the entries in the database table. 

In line 28, all the entries in the database table are selected and passed as an object to the home.html file.


In this home.html file, two input fields are created. One input field is to get the input and insert a row in the database table and the other input field is used to get the input and delete a row in the database table. A table is also created in this home.html file to display the rows in the database. 

Do check out the official documentation of Flask-SQLAlchemy to know more about the complex queries and executing them in the flask.

Creating users:
Viewing the rows after inserting:
Deleting and viewing the rows in the database:

And there have it again! It is as simple as that! We've learned how to work with databases using flask! 


And here we come to the end of the flask for dummies blog series. All the demos and explanations are minimal and might help you get a piece of basic knowledge of flask. Try working on complex projects and get to know the deep concepts of the flask. Do follow our blog if you haven't already for more such informative articles.