wtforms.rst
This file
Path
docs/patterns/wtforms.rst
124 lines · 4.6 KiB
Last changed by
Added links to Flask-WTF and Flask-SQLAlchemy. This fixes #73Armin Ronacherbefore adoptiond0357b4
History of this fileTake it
Added WTForms documentation.Armin Ronacherbefore adoptionce18d45
lines 1–5why, one step back1Form 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 designedForgot to link the website.Armin Ronacherbefore adoption166f5ed
line 6why, one step back6to make this process easier to manage. One of them is `WTForms`_ which weAdded WTForms documentation.Armin Ronacherbefore adoptionce18d45
lines 7–14why, one step back7will 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.14Added links to Flask-WTF and Flask-SQLAlchemy. This fixes #73Armin Ronacherbefore adoptiond0357b4
lines 15–23why, one step back15.. admonition:: Getting most of WTForms with an Extension1617 The `Flask-WTF`_ extension expands on this pattern and adds a few18 handful little helpers that make working with forms and Flask more19 fun. You can get it from `PyPI20 <http://pypi.python.org/pypi/Flask-WTF>`_.2122.. _Flask-WTF: http://packages.python.org/Flask-WTF/23Added WTForms documentation.Armin Ronacherbefore adoptionce18d45
lines 24–33why, one step back24The Forms25---------2627This is an example form for a typical registration page::2829 from wtforms import Form, BooleanField, TextField, validators3031 class RegistrationForm(Form):32 username = TextField('Username', [validators.Length(min=4, max=25)])33 email = TextField('Email Address', [validators.Length(min=6, max=35)])Corrected validator usage in the wtforms docs.Armin Ronacherbefore adoptiondc3f13d
lines 34–38why, one step back34 password = PasswordField('New Password', [35 validators.Required(),36 validators.EqualTo('confirm', message='Passwords must match')37 ])38 confirm = PasswordField('Repeat Password')Added WTForms documentation.Armin Ronacherbefore adoptionce18d45
lines 39–53why, one step back39 accept_tos = BooleanField('I accept the TOS', [validators.Required()])4041In 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')Fixed merging confictArmin Ronacherbefore adoptioneeb0e94
line 54why, one step back54 return redirect(url_for('login'))Added WTForms documentation.Armin Ronacherbefore adoptionce18d45
lines 55–86why, one step back55 return render_template('register.html', form=form)5657Notice that we are implying that the view is using SQLAlchemy here58(:ref:`sqlalchemy-pattern`) but this is no requirement of course. Adapt59the code as necessary.6061Things to remember:62631. create the form from the request :attr:`~flask.request.form` value if64 the data is submitted via the HTTP `POST` method and65 :attr:`~flask.request.args` if the data is submitted as `GET`.662. to validate the data, call the :func:`~wtforms.form.Form.validate`67 method which will return `True` if the data validates, `False`68 otherwise.693. to access individual values from the form, access `form.<NAME>.data`.7071Forms in Templates72------------------7374Now to the template side. When you pass the form to the templates you can75easily render them there. Look at the following example template to see76how 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.7980Here an example `_formhelpers.html` template with such a macro:8182.. sourcecode:: html+jinja8384 {% macro render_field(field) %}85 <dt>{{ field.label }}86 <dd>{{ field(**kwargs)|safe }}Fixed indentation of an example.Armin Ronacherbefore adoption56675b3
lines 87–92why, one step back87 {% if field.errors %}88 <ul class="errors">89 {% for error in field.errors %}<li>{{ error }}{% endfor %}90 </ul>91 {% endif %}92 </dd>Added WTForms documentation.Armin Ronacherbefore adoptionce18d45
lines 93–108why, one step back93 {% endmacro %}9495This macro accepts a couple of keyword arguments that are forwarded to96WTForm's field function that renders the field for us. They keyword97arguments will be inserted as HTML attributes. So for example you can98call ``render_field(form.username, class='username')`` to add a class to99the input element. Note that WTForms returns standard Python unicode100strings, so we have to tell Jinja2 that this data is already HTML escaped101with the `|safe` filter.102103Here the `register.html` template for the function we used above which104takes advantage of the `_formhelpers.html` template:105106.. sourcecode:: html+jinja107108 {% from "_formhelpers.html" import render_field %}POST -> post in HTMLArmin Ronacherbefore adoption4ff9493
line 109why, one step back109 <form method="post" action="/register">Added WTForms documentation.Armin Ronacherbefore adoptionce18d45
lines 110–118why, one step back110 <dl>111 {{ render_field(form.username) }}112 {{ render_field(form.email) }}113 {{ render_field(form.password) }}114 {{ render_field(form.confirm) }}115 {{ render_field(form.accept_tos) }}116 </dl>117 <p><input type=submit value=Register>118 </form>Added links for SQLAlchemy and WTForms.Armin Ronacherbefore adoption976e792
lines 119–122why, one step back119120For more information about WTForms, head over to the `WTForms121website`_.122Forgot to link the website.Armin Ronacherbefore adoption166f5ed
line 123why, one step back123.. _WTForms: http://wtforms.simplecodes.com/Added links for SQLAlchemy and WTForms.Armin Ronacherbefore adoption976e792
line 124why, one step back124.. _WTForms website: http://wtforms.simplecodes.com/