Flask-WTF explained & how to use it?
In this tutorial, we are going to learn about the Flask-WTF extension. We are also going to learn why is this extension important for any basic website also. Also, we are going to learn how to implement this in our webpages.
Flask – WTF
A very important aspect of any good webpage is the user interface it provides to the users. For this purpose, HTML provides us with <form> tag, used to design that very user interface for forms.
The data entered by a user in the form object is then submitted by him in the form of an HTTP request to the server-side by using two methods – GET and POST.
- The form elements from HTTP request data is recreated every time. So to do that, the form elements are created twice – once in the HTML form and the second time in the server-side script.
- An HTML form elements are difficult to load dynamically, so it becomes another disadvantage of using HTML form elements. So, there’s not a way provided by HTML itself to validate a user’s input.
And here the WTForms library of Flask comes to our rescue. So we can use all the functionalities of WTForms through an extension known as Flask-WTF.
We can define the form fields in our Python code and render it through the HTML template, using the Flask-WTF extension. We can also apply validation to our forms using the Flask-WTF extension.
So let us all these in action!
But first of all, we need to install the extension.
Install flask-WTF extension
pip install flask-WTF
In this way, we can install flask-WTF via pip.
Form fields in Flask-WTF –
- TextField – Used to represent <input type = ‘text’> HTML form element
- BooleanField – Used to represent <input type = ‘checkbox’> HTML form element
- DecimalField – It’s a textfield for displaying number with decimals
- IntegerField – It’s a textField for displaying integer
- RadioField – Used to represent <input type = ‘radio’> HTML form element
- SelectField – Used to represent select form element
- TextAreaField – Used to represent <testarea> html form element
- PasswordField – Used to represent <input type = ‘password’> HTML form element
- SubmitField – Used to represent <input type = ‘submit’> form element
- DataRequired – Used to check whether input field is empty
- Email – Used to check whether text in the field follows email ID conventions
- IPAddress – Used to validate IP address in input field
- Length – Used to verify if length of string in input field is in given range
- NumberRange – Used to validate a number in input field within given range
- URL – Used to validate URL entered in input field
So we can use the Flask-WTF extension for implementing form elements in our webpages instead of using the standard set of HTML form tag.
I hope you understood what was explained in this tutorial. If you have any doubts or queries regarding anything described here, please feel free to comment them down below.
You can also read: