Skip to content
Myr

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

6 files+115 added−10 removed

modified:docs/patterns/flashing.rst+2 added
1.. _message-flashing-pattern:23Message Flashing4================56Good applications and user interfaces are all about feedback. If the user
75 unmodified lines
modified:docs/patterns/index.rst+1 added
14 unmodified lines
1516 packages17 sqlite318 sqlalchemy19 wtforms20 templateinheritance21 flashing
added:docs/patterns/wtforms.rst+109 added
1Form Validation with WTForms2============================34When you have to work with form data submitted by a browser view code5quickly becomes very hard to read. There are libraries out there designed6to 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 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)])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()])2930In the View31-----------3233In the view function, the usage of this form looks like this::3435 @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)4546Notice that we are implying that the view is using SQLAlchemy here47(:ref:`sqlalchemy-pattern`) but this is no requirement of course. Adapt48the code as necessary.4950Things to remember:51521. 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`.552. to validate the data, call the :func:`~wtforms.form.Form.validate`56 method which will return `True` if the data validates, `False`57 otherwise.583. to access individual values from the form, access `form.<NAME>.data`.5960Forms in Templates61------------------6263Now to the template side. When you pass the form to the templates you can64easily render them there. Look at the following example template to see65how easy this is. WTForms does half the form generation for us already.66To make it even nicer, we can write a macro that renders a field with67label and a list of errors if there are any.6869Here an example `_formhelpers.html` template with such a macro:7071.. sourcecode:: html+jinja7273 {% 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 %}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 %}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 lines
241242intersphinx_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 lines
95 sudo easy_install Flask9697(Run it in an Admin shell on Windows systems and without the `sudo`).9899100The Drop into Place Version101---------------------------102103Now I really don't recommend this way on using Flask, but you can do that104of course as well. Download the `dip` zipfile from the website and unzip105it next to your application.10699.. _windows-easy-install:100101`easy_install` on Windows102-------------------------
29 unmodified lines
modified:docs/quickstart.rst+1 added-1 removed
366 unmodified lines
367u'Marked up \xbb HTML'368369.. [#] 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.373374375Accessing Request Data
256 unmodified lines