Skip to content
Myr

wtforms.rst

This file

Path

docs/patterns/wtforms.rst

115 lines · 4.2 KiB

Last changed by

Fixed merging confictArmin Ronacherbefore adoptioneeb0e94

History of this file

Take it

Added WTForms documentation.Armin Ronacherbefore adoptionce18d45

lines 1–5why, one step back
1Form Validation with WTForms
2============================34When you have to work with form data submitted by a browser view code5quickly becomes very hard to read. There are libraries out there designed

Forgot to link the website.Armin Ronacherbefore adoption166f5ed

line 6why, one step back
6to make this process easier to manage. One of them is `WTForms`_ which we

Added WTForms documentation.Armin Ronacherbefore adoptionce18d45

lines 7–24why, one step back
7will handle here. If you find yourself in the situation of having many
8forms, you might want to give it a try.910When you are working with WTForms you have to define your forms as classes11first. I recommend breaking up the application into multiple modules 12(:ref:`larger-applications`) for that and adding a separate module for the13forms.1415The Forms16---------1718This is an example form for a typical registration page::1920 from wtforms import Form, BooleanField, TextField, validators2122 class RegistrationForm(Form):23 username = TextField('Username', [validators.Length(min=4, max=25)])24 email = TextField('Email Address', [validators.Length(min=6, max=35)])

Corrected validator usage in the wtforms docs.Armin Ronacherbefore adoptiondc3f13d

lines 25–29why, one step back
25 password = PasswordField('New Password', [
26 validators.Required(),27 validators.EqualTo('confirm', message='Passwords must match')28 ])29 confirm = PasswordField('Repeat Password')

Added WTForms documentation.Armin Ronacherbefore adoptionce18d45

lines 30–44why, one step back
30 accept_tos = BooleanField('I accept the TOS', [validators.Required()])
3132In the View33-----------3435In the view function, the usage of this form looks like this::3637 @app.route('/register', methods=['GET', 'POST'])38 def register():39 form = RegistrationForm(request.form)40 if request.method == 'POST' and form.validate():41 user = User(form.username.data, form.email.data,42 form.password.data)43 db_session.add(user)44 flash('Thanks for registering')

Fixed merging confictArmin Ronacherbefore adoptioneeb0e94

line 45why, one step back
45 return redirect(url_for('login'))

Added WTForms documentation.Armin Ronacherbefore adoptionce18d45

lines 46–77why, one step back
46 return render_template('register.html', form=form)
4748Notice that we are implying that the view is using SQLAlchemy here49(:ref:`sqlalchemy-pattern`) but this is no requirement of course. Adapt50the code as necessary.5152Things to remember:53541. create the form from the request :attr:`~flask.request.form` value if55 the data is submitted via the HTTP `POST` method and56 :attr:`~flask.request.args` if the data is submitted as `GET`.572. to validate the data, call the :func:`~wtforms.form.Form.validate`58 method which will return `True` if the data validates, `False`59 otherwise.603. to access individual values from the form, access `form.<NAME>.data`.6162Forms in Templates63------------------6465Now to the template side. When you pass the form to the templates you can66easily render them there. Look at the following example template to see67how easy this is. WTForms does half the form generation for us already.68To make it even nicer, we can write a macro that renders a field with69label and a list of errors if there are any.7071Here an example `_formhelpers.html` template with such a macro:7273.. sourcecode:: html+jinja7475 {% macro render_field(field) %}76 <dt>{{ field.label }}77 <dd>{{ field(**kwargs)|safe }}

Fixed indentation of an example.Armin Ronacherbefore adoption56675b3

lines 78–83why, one step back
78 {% if field.errors %}
79 <ul class="errors">80 {% for error in field.errors %}<li>{{ error }}{% endfor %}81 </ul>82 {% endif %}83 </dd>

Added WTForms documentation.Armin Ronacherbefore adoptionce18d45

lines 84–99why, one step back
84 {% endmacro %}
8586This macro accepts a couple of keyword arguments that are forwarded to87WTForm's field function that renders the field for us. They keyword88arguments will be inserted as HTML attributes. So for example you can89call ``render_field(form.username, class='username')`` to add a class to90the input element. Note that WTForms returns standard Python unicode91strings, so we have to tell Jinja2 that this data is already HTML escaped92with the `|safe` filter.9394Here the `register.html` template for the function we used above which95takes advantage of the `_formhelpers.html` template:9697.. sourcecode:: html+jinja9899 {% from "_formhelpers.html" import render_field %}

POST -> post in HTMLArmin Ronacherbefore adoption4ff9493

line 100why, one step back
100 <form method="post" action="/register">

Added WTForms documentation.Armin Ronacherbefore adoptionce18d45

lines 101–109why, one step back
101 <dl>
102 {{ render_field(form.username) }}103 {{ render_field(form.email) }}104 {{ render_field(form.password) }}105 {{ render_field(form.confirm) }}106 {{ render_field(form.accept_tos) }}107 </dl>108 <p><input type=submit value=Register>109 </form>

Added links for SQLAlchemy and WTForms.Armin Ronacherbefore adoption976e792

lines 110–113why, one step back
110
111For more information about WTForms, head over to the `WTForms112website`_.113

Forgot to link the website.Armin Ronacherbefore adoption166f5ed

line 114why, one step back
114.. _WTForms: http://wtforms.simplecodes.com/

Added links for SQLAlchemy and WTForms.Armin Ronacherbefore adoption976e792

line 115why, one step back
115.. _WTForms website: http://wtforms.simplecodes.com/