wtforms.rst
This file
Path
docs/patterns/wtforms.rst
113 lines · 4.2 KiB
Last changed by
Forgot to link the website.Armin Ronacherbefore adoption166f5ed
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–75why, 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.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 }}Fixed indentation of an example.Armin Ronacherbefore adoption56675b3
lines 76–81why, one step back76 {% if field.errors %}77 <ul class="errors">78 {% for error in field.errors %}<li>{{ error }}{% endfor %}79 </ul>80 {% endif %}81 </dd>Added WTForms documentation.Armin Ronacherbefore adoptionce18d45
lines 82–107why, one step back82 {% endmacro %}8384This macro accepts a couple of keyword arguments that are forwarded to85WTForm's field function that renders the field for us. They keyword86arguments will be inserted as HTML attributes. So for example you can87call ``render_field(form.username, class='username')`` to add a class to88the input element. Note that WTForms returns standard Python unicode89strings, so we have to tell Jinja2 that this data is already HTML escaped90with the `|safe` filter.9192Here the `register.html` template for the function we used above which93takes advantage of the `_formhelpers.html` template:9495.. sourcecode:: html+jinja9697 {% from "_formhelpers.html" import render_field %}98 <form method="POST" action="/register">99 <dl>100 {{ render_field(form.username) }}101 {{ render_field(form.email) }}102 {{ render_field(form.password) }}103 {{ render_field(form.confirm) }}104 {{ render_field(form.accept_tos) }}105 </dl>106 <p><input type=submit value=Register>107 </form>Added links for SQLAlchemy and WTForms.Armin Ronacherbefore adoption976e792
lines 108–111why, one step back108109For more information about WTForms, head over to the `WTForms110website`_.111Forgot to link the website.Armin Ronacherbefore adoption166f5ed
line 112why, one step back112.. _WTForms: http://wtforms.simplecodes.com/Added links for SQLAlchemy and WTForms.Armin Ronacherbefore adoption976e792
line 113why, one step back113.. _WTForms website: http://wtforms.simplecodes.com/