Flask-WTForms

wtform (vecteezy image)

Quickstart

1. Installation

pip install WTForms
pip install Flask-WTF

2. create form

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField
from wtforms.validators import DataRequired, Email, Length
class LoginForm(FlaskForm):
email = StringField(label='email', validators=[DataRequired()])
password = PasswordField(label='password', validators=[DataRequired()])

3. create secret key

app.config['SECRET_KEY'] = 'secret'

4. passing form

@app.route("/", methods=['GET', 'POST'])
def login():
form = LoginForm()
if request.method == 'POST':
print(request.form['email'])
print(request.form['password'])
return redirect(url_for("success", email=request.form['email']))
return render_template("login.html", form=form)
<form method="POST" action="{{url_for('login')}}">
{{ form.csrf_token }}
{{ form.email.label }}
{{ form.email }}<br>
{{ form.password.label }}
{{ form.password }}<br>
<button type="submit">Login</button>
</form>

5. Check csrf_token

@app.route("/", methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
print(request.form['email'])
print(request.form['password'])
return redirect(url_for("success", email=request.form['email']))
return render_template("login.html", form=form)

Create form

from flask_wtf import FlaskForm
from wtforms import PasswordField
from wtforms.fields.html5 import EmailField
from wtforms.validators import DataRequired, Email, Length
class LoginForm(FlaskForm):
email = EmailField(label='email', validators=[DataRequired()])
password = PasswordField(label='password', validators=[DataRequired()])
wtform works on browser

Csrf_token

Check CSRF Token

@app.route("/", methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
print(request.form['email'])
print(request.form['password'])
return redirect(url_for("success", email=request.form['email']))
return render_template("login.html", form=form)

Fields

  • Label ➜ label of the fields
  • Validators ➜ validators check input if it is validate. (for example, minium password is 7 characters) wtforms validators

1. Password Field

from wtforms import PasswordFieldpassword = PasswordField(label='password', validators=[DataRequired()])
form.password.data

2. Text Field

from wtforms import TextFieldname = TextField(label='name', validators=[DataRequired()])
form.name.data]

3. BooleanField

from wtforms import BooleanFieldagree = BooleanField(label='agree')
form.agree.data

4. Text area Field

from wtforms import TextAreaFieldcomment = TextAreaField(label='comment')
form.comment.data

5. Select Field

<select id="colors" name="colors">
<option value="red">red color</option>
<option value="blue">blue color</option>
<option value="yellow">yellow color</option>
</select>
from wtforms import SelectFieldcolors = SelectField(label='color', choices=[('red', 'red color'), ('blue', 'blue color'), ('yellow', 'yellow color')])
form.colors.data

6. Radio Field

<input id="genders-0" name="genders" type="radio" value="female">
<label for="genders-0">female</label>
<input id="genders-1" name="genders" type="radio" value="male">
<label for="genders-1">male</label>
from wtforms import RadioFieldgenders = RadioField(label='gender', choices=[('female', 'female'), ('male', 'male')])
{% for gender in form.genders %}
<tr>
<td>{{ gender }}</td>
<td>{{ gender.label }}</td>
</tr>
{% endfor %}

7. Email Fields

from wtforms.fields.html5 import EmailFieldemail = EmailField(label='email', validators=[DataRequired()])
form.email.data

8. File Field

from werkzeug.utils import secure_filename
from flask_wtf.file import FileField
logo = FileField(label='logo')
if form.validate_on_submit():
filename = secure_filename(form.logo.data.filename)
return redirect(url_for("success", email=request.form['email']))
else:
filename = None
<form method="POST" action="{{url_for('login')}}" enctype="multipart/form-data">

9. Multiple File Fields

from wtforms import PasswordField, MultipleFileFieldimages = MultipleFileField(label='images upload')
form.images.data

Validators

  • passing validators as fields parameter
  • error messages with flash messages

1. DataRequired

from wtforms.validators import DataRequiredemail = EmailField(label='email', validators=[DataRequired()])

2. Email

  • passing validators as fields parameter (main.py)
from wtforms.validators import DataRequired, Emailemail = EmailField(label='email', validators=[DataRequired(), Email(message='Invalid Email')])
  • errors messages with flash messages (login.html)
{{ form.email.label }}
{{ form.email }}<br>
{% if form.errors %}
<ul class=errors>
{% for error in form.errors['email'] %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
invalid email

3. Length of string

  • passing validators as fields parameter (main.py)
from wtforms.validators import DataRequired, Email, Lengthpassword = PasswordField(label='password', validators=[DataRequired(), Length(min=5, max=20, message="min 5 and max 20")])
  • showing validation errors with flash messages (login.html)
{{ form.password.label }}
{{ form.password }}<br>
{% if form.errors %}
<ul class=errors>
{% for error in form.errors['password'] %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}

4. File Required

  • passing validators as fields parameter (main.py)
from flask_wtf.file import FileField, FileRequiredimage = FileField(label='image upload', validators=[FileRequired()])

--

--

Learning javascript and web-development

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