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 fileTake it
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', [26 validators.Required(),27 validators.EqualTo('confirm', message='Passwords must match')28 ])29 confirm = PasswordField('Repeat Password')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')45 return redirect(url_for('login'))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 }}78 {% if field.errors %}79 <ul class="errors">80 {% for error in field.errors %}<li>{{ error }}{% 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>110111For more information about WTForms, head over to the `WTForms112website`_.113114.. _WTForms: http://wtforms.simplecodes.com/115.. _WTForms website: http://wtforms.simplecodes.com/