How to define, render and validate a Form using Flask's Flask-WTF
class AnimalForm(FlaskForm):
name = StringField('name', validators=[validators.Required(), validators.length(max=30)])
kind = StringField('kind', validators=[validators.Required(), validators.length(max=10)])
description = TextAreaField('description', validators=[])
--Create by inheriting FlaskForm --Multiple validators can be passed to validators
<form method="POST">
<p>{{ form.name.label }}:{{ form.name(size=30) }}</p>
<p>{{ form.kind.label }}:{{ form.kind(size=20) }}</p>
<p>{{ form.description.label }}:{{ form.description(cols="50", rows="20") }}</p>
<button type="submit">Submit</button>
</form>
--You can get the name defined in form by accessing label --Each field is callable and renders HTML --When rendering a field, if you pass an argument, it will be converted to an HTML property.
form = AnimalForm()
if form.validate_on_submit():
name = form.name.data
kind = form.kind.data
description = form.description.data
--valid_on_submit checks whether it is a post and validates the data --You can get the validated data by accessing data
Recommended Posts