Skip to content
Myr

wtforms.rst

This file

Path

docs/patterns/wtforms.rst

126 lines · 4.6 KiB

Last changed by

resolve merge conflictsKenneth Reitzbefore adoption31174fe

History of this file

Take it

The walk stopped after 200 commits: lines older than e9d1fc4 point at it.

Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4

lines 1–3why, one step back
1Form Validation with WTForms
2============================3

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 4why, one step back
4When you have to work with form data submitted by a browser view, code

Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4

lines 5–10why, one step back
5quickly becomes very hard to read. There are libraries out there designed
6to make this process easier to manage. One of them is `WTForms`_ which we7will handle here. If you find yourself in the situation of having many8forms, you might want to give it a try.910When you are working with WTForms you have to define your forms as classes

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption67e4d3e

line 11why, one step back
11first. I recommend breaking up the application into multiple modules

Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4

lines 12–14why, one step back
12(:ref:`larger-applications`) for that and adding a separate module for the
13forms.14

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 15why, one step back
15.. admonition:: Getting the most out of WTForms with an Extension

Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4

line 16why, one step back
16

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 17–18why, one step back
17 The `Flask-WTF`_ extension expands on this pattern and adds a
18 few little helpers that make working with forms and Flask more

Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4

line 19why, one step back
19 fun. You can get it from `PyPI

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption67e4d3e

line 20why, one step back
20 <https://pypi.python.org/pypi/Flask-WTF>`_.

Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4

line 21why, one step back
21

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 22why, one step back
22.. _Flask-WTF: https://flask-wtf.readthedocs.io/en/stable/

Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4

lines 23–28why, one step back
23
24The Forms25---------2627This is an example form for a typical registration page::28

Merge pull request #1315 from brettgerry/deprecate-textfieldMarkus Unterwaditzerbefore adoptiondfeabb7

line 29why, one step back
29 from wtforms import Form, BooleanField, StringField, PasswordField, validators

Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4

lines 30–31why, one step back
30
31 class RegistrationForm(Form):

Merge pull request #1315 from brettgerry/deprecate-textfieldMarkus Unterwaditzerbefore adoptiondfeabb7

lines 32–33why, one step back
32 username = StringField('Username', [validators.Length(min=4, max=25)])
33 email = StringField('Email Address', [validators.Length(min=6, max=35)])

Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4

line 34why, one step back
34 password = PasswordField('New Password', [

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 35why, one step back
35 validators.DataRequired(),

Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4

lines 36–38why, one step back
36 validators.EqualTo('confirm', message='Passwords must match')
37 ])38 confirm = PasswordField('Repeat Password')

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 39why, one step back
39 accept_tos = BooleanField('I accept the TOS', [validators.DataRequired()])

Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4

lines 40–56why, one step back
40
41In the View42-----------4344In the view function, the usage of this form looks like this::4546 @app.route('/register', methods=['GET', 'POST'])47 def register():48 form = RegistrationForm(request.form)49 if request.method == 'POST' and form.validate():50 user = User(form.username.data, form.email.data,51 form.password.data)52 db_session.add(user)53 flash('Thanks for registering')54 return redirect(url_for('login'))55 return render_template('register.html', form=form)56

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 57–58why, one step back
57Notice we're implying that the view is using SQLAlchemy here
58(:ref:`sqlalchemy-pattern`), but that's not a requirement, of course. Adapt

Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4

lines 59–63why, one step back
59the code as necessary.
6061Things to remember:62631. create the form from the request :attr:`~flask.request.form` value if

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

lines 64–65why, one step back
64 the data is submitted via the HTTP ``POST`` method and
65 :attr:`~flask.request.args` if the data is submitted as ``GET``.

Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4

line 66why, one step back
662. to validate the data, call the :func:`~wtforms.form.Form.validate`

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 67why, one step back
67 method, which will return ``True`` if the data validates, ``False``

Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4

lines 68–73why, one step back
68 otherwise.
693. to access individual values from the form, access `form.<NAME>.data`.7071Forms in Templates72------------------73

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 74why, one step back
74Now to the template side. When you pass the form to the templates, you can

Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4

lines 75–79why, one step back
75easily render them there. Look at the following example template to see
76how easy this is. WTForms does half the form generation for us already.77To make it even nicer, we can write a macro that renders a field with78label and a list of errors if there are any.79

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 80why, one step back
80Here's an example :file:`_formhelpers.html` template with such a macro:

Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4

lines 81–97why, one step back
81
82.. sourcecode:: html+jinja8384 {% macro render_field(field) %}85 <dt>{{ field.label }}86 <dd>{{ field(**kwargs)|safe }}87 {% if field.errors %}88 <ul class=errors>89 {% for error in field.errors %}90 <li>{{ error }}</li>91 {% endfor %}92 </ul>93 {% endif %}94 </dd>95 {% endmacro %}9697This macro accepts a couple of keyword arguments that are forwarded to

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 98–99why, one step back
98WTForm's field function, which renders the field for us. The keyword
99arguments will be inserted as HTML attributes. So, for example, you can

Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4

lines 100–101why, one step back
100call ``render_field(form.username, class='username')`` to add a class to
101the input element. Note that WTForms returns standard Python unicode

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 102why, one step back
102strings, so we have to tell Jinja2 that this data is already HTML-escaped

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 103why, one step back
103with the ``|safe`` filter.

Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4

line 104why, one step back
104

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 105why, one step back
105Here is the :file:`register.html` template for the function we used above, which

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 106why, one step back
106takes advantage of the :file:`_formhelpers.html` template:

Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4

lines 107–110why, one step back
107
108.. sourcecode:: html+jinja109110 {% from "_formhelpers.html" import render_field %}

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 111why, one step back
111 <form method=post>

Updated docs for click supportArmin Ronacherbefore adoptione9d1fc4

lines 112–124why, one step back
112 <dl>
113 {{ render_field(form.username) }}114 {{ render_field(form.email) }}115 {{ render_field(form.password) }}116 {{ render_field(form.confirm) }}117 {{ render_field(form.accept_tos) }}118 </dl>119 <p><input type=submit value=Register>120 </form>121122For more information about WTForms, head over to the `WTForms123website`_.124

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 125–126why, one step back
125.. _WTForms: https://wtforms.readthedocs.io/
126.. _WTForms website: https://wtforms.readthedocs.io/