Debian Codegraph @

docs/quickstart.rst

raw
1 Quickstart
2 ==========
3
4 Eager to get started? This page gives a good introduction to Flask-WTF.
5 It assumes you already have Flask-WTF installed. If you do not, head over
6 to the :doc:`install` section.
7
8
9 Creating Forms
10 --------------
11
12 Flask-WTF provides your Flask application integration with WTForms. For example::
13
14 from flask_wtf import FlaskForm
15 from wtforms import StringField
16 from wtforms.validators import DataRequired
17
18 class MyForm(FlaskForm):
19 name = StringField('name', validators=[DataRequired()])
20
21
22 .. note::
23
24 From version 0.9.0, Flask-WTF will not import anything from wtforms,
25 you need to import fields from wtforms.
26
27 In addition, a CSRF token hidden field is created automatically. You can
28 render this in your template:
29
30 .. sourcecode:: html+jinja
31
32 <form method="POST" action="/">
33 {{ form.csrf_token }}
34 {{ form.name.label }} {{ form.name(size=20) }}
35 <input type="submit" value="Go">
36 </form>
37
38 If your form has multiple hidden fields, you can render them in one
39 block using :meth:`~flask_wtf.FlaskForm.hidden_tag`.
40
41 .. sourcecode:: html+jinja
42
43 <form method="POST" action="/">
44 {{ form.hidden_tag() }}
45 {{ form.name.label }} {{ form.name(size=20) }}
46 <input type="submit" value="Go">
47 </form>
48
49
50 Validating Forms
51 ----------------
52
53 Validating the request in your view handlers::
54
55 @app.route('/submit', methods=['GET', 'POST'])
56 def submit():
57 form = MyForm()
58 if form.validate_on_submit():
59 return redirect('/success')
60 return render_template('submit.html', form=form)
61
62 Note that you don't have to pass ``request.form`` to Flask-WTF; it will
63 load automatically. And the convenient ``validate_on_submit`` will check
64 if it is a POST request and if it is valid.
65
66 If your forms include validation, you'll need to add to your template to display
67 any error messages. Using the ``form.name`` field from the example above, that
68 would look like this:
69
70 .. sourcecode:: html+jinja
71
72 {% if form.name.errors %}
73 <ul class="errors">
74 {% for error in form.name.errors %}
75 <li>{{ error }}</li>
76 {% endfor %}
77 </ul>
78 {% endif %}
79
80 Heading over to :doc:`form` to learn more skills.