Added WTForms documentation.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent 73a47a0 · Browse files · 6 files·+115 added−10 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+115 added−10 removed
- other:+115 added−10 removed
Provenance
- Commit
ce18d45- Tree
469af8d- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
73a47a0
6 files changed+115 added−10 removed
modified:docs/patterns/flashing.rst+2 added
1+.. _message-flashing-pattern:2+3 Message Flashing4 ================5 6 Good applications and user interfaces are all about feedback. If the user75 unmodified linesmodified:docs/patterns/index.rst+1 added
14 unmodified lines15 16 packages17 sqlite318 sqlalchemy19+ wtforms20 templateinheritance21 flashingadded:docs/patterns/wtforms.rst+109 added
1+Form Validation with WTForms2+============================3+4+When you have to work with form data submitted by a browser view code5+quickly becomes very hard to read. There are libraries out there designed6+to make this process easier to manage. One of them is WTForms which we7+will handle here. If you find yourself in the situation of having many8+forms, you might want to give it a try.9+10+When you are working with WTForms you have to define your forms as classes11+first. I recommend breaking up the application into multiple modules 12+(:ref:`larger-applications`) for that and adding a separate module for the13+forms.14+15+The Forms16+---------17+18+This is an example form for a typical registration page::19+20+ from wtforms import Form, BooleanField, TextField, validators21+22+ class RegistrationForm(Form):23+ username = TextField('Username', [validators.Length(min=4, max=25)])24+ email = TextField('Email Address', [validators.Length(min=6, max=35)])25+ password = PasswordField('New Password', [Required(),26+ EqualTo('confirm', mesage='Passwords must match')])27+ confirm = PasswordField('Repeat Password')28+ accept_tos = BooleanField('I accept the TOS', [validators.Required()])29+30+In the View31+-----------32+33+In the view function, the usage of this form looks like this::34+35+ @app.route('/register', methods=['GET', 'POST'])36+ def register():37+ form = RegistrationForm(request.form)38+ if request.method == 'POST' and form.validate():39+ user = User(form.username.data, form.email.data,40+ form.password.data)41+ db_session.add(user)42+ flash('Thanks for registering')43+ redirect(url_for('login'))44+ return render_template('register.html', form=form)45+46+Notice that we are implying that the view is using SQLAlchemy here47+(:ref:`sqlalchemy-pattern`) but this is no requirement of course. Adapt48+the code as necessary.49+50+Things to remember:51+52+1. create the form from the request :attr:`~flask.request.form` value if53+ the data is submitted via the HTTP `POST` method and54+ :attr:`~flask.request.args` if the data is submitted as `GET`.55+2. to validate the data, call the :func:`~wtforms.form.Form.validate`56+ method which will return `True` if the data validates, `False`57+ otherwise.58+3. to access individual values from the form, access `form.<NAME>.data`.59+60+Forms in Templates61+------------------62+63+Now to the template side. When you pass the form to the templates you can64+easily render them there. Look at the following example template to see65+how easy this is. WTForms does half the form generation for us already.66+To make it even nicer, we can write a macro that renders a field with67+label and a list of errors if there are any.68+69+Here an example `_formhelpers.html` template with such a macro:70+71+.. sourcecode:: html+jinja72+73+ {% macro render_field(field) %}74+ <dt>{{ field.label }}75+ <dd>{{ field(**kwargs)|safe }}76+ {% if field.errors %}77+ <ul class="errors">78+ {% for error in field.errors %}79+ <li>{{ error }}</li>80+ {% endfor %}81+ </ul>82+ {% endif %}83+ </dd>84+ {% endmacro %}85+86+This macro accepts a couple of keyword arguments that are forwarded to87+WTForm's field function that renders the field for us. They keyword88+arguments will be inserted as HTML attributes. So for example you can89+call ``render_field(form.username, class='username')`` to add a class to90+the input element. Note that WTForms returns standard Python unicode91+strings, so we have to tell Jinja2 that this data is already HTML escaped92+with the `|safe` filter.93+94+Here the `register.html` template for the function we used above which95+takes advantage of the `_formhelpers.html` template:96+97+.. sourcecode:: html+jinja98+99+ {% from "_formhelpers.html" import render_field %}100+ <form method="POST" action="/register">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>modified:docs/conf.py+2 added-1 removed
240 unmodified lines241 242 intersphinx_mapping = {243 'http://docs.python.org/dev': None,244 'http://werkzeug.pocoo.org/documentation/dev/': None,245- 'http://www.sqlalchemy.org/docs/': None245+ 'http://www.sqlalchemy.org/docs/': None,246+ 'http://wtforms.simplecodes.com/docs/0.5/': None247 }modified:docs/installation.rst-8 removed
94 unmodified lines95 sudo easy_install Flask96 97 (Run it in an Admin shell on Windows systems and without the `sudo`).98 99-100-The Drop into Place Version101----------------------------102-103-Now I really don't recommend this way on using Flask, but you can do that104-of course as well. Download the `dip` zipfile from the website and unzip105-it next to your application.106-99 .. _windows-easy-install:100 101 `easy_install` on Windows102 -------------------------29 unmodified linesmodified:docs/quickstart.rst+1 added-1 removed
366 unmodified lines367 u'Marked up \xbb HTML'368 369 .. [#] Unsure what that :class:`~flask.g` object is? It's something you370 can store information on yourself, check the documentation of that371- object (:class:`~flask.g`) and the :ref:`database-pattern` for more371+ object (:class:`~flask.g`) and the :ref:`sqlite3` for more372 information.373 374 375 Accessing Request Data256 unmodified lines