| 1 |
Creating Forms |
| 2 |
============== |
| 3 |
|
| 4 |
Secure Form |
| 5 |
----------- |
| 6 |
|
| 7 |
.. currentmodule:: flask_wtf |
| 8 |
|
| 9 |
Without any configuration, the :class:`FlaskForm` will be a session secure |
| 10 |
form with csrf protection. We encourage you not to change this. |
| 11 |
|
| 12 |
But if you want to disable the csrf protection, you can pass:: |
| 13 |
|
| 14 |
form = FlaskForm(meta={'csrf': False}) |
| 15 |
|
| 16 |
You can disable it globally—though you really shouldn't—with the |
| 17 |
configuration:: |
| 18 |
|
| 19 |
WTF_CSRF_ENABLED = False |
| 20 |
|
| 21 |
In order to generate the csrf token, you must have a secret key, this |
| 22 |
is usually the same as your Flask app secret key. If you want to use |
| 23 |
another secret key, config it:: |
| 24 |
|
| 25 |
WTF_CSRF_SECRET_KEY = 'a random string' |
| 26 |
|
| 27 |
|
| 28 |
File Uploads |
| 29 |
------------ |
| 30 |
|
| 31 |
.. currentmodule:: flask_wtf.file |
| 32 |
|
| 33 |
The :class:`FileField` provided by Flask-WTF differs from the WTForms-provided |
| 34 |
field. It will check that the file is a non-empty instance of |
| 35 |
:class:`~werkzeug.datastructures.FileStorage`, otherwise ``data`` will be |
| 36 |
``None``. :: |
| 37 |
|
| 38 |
from flask_wtf import FlaskForm |
| 39 |
from flask_wtf.file import FileField, FileRequired |
| 40 |
from werkzeug.utils import secure_filename |
| 41 |
|
| 42 |
class PhotoForm(FlaskForm): |
| 43 |
photo = FileField(validators=[FileRequired()]) |
| 44 |
|
| 45 |
@app.route('/upload', methods=['GET', 'POST']) |
| 46 |
def upload(): |
| 47 |
form = PhotoForm() |
| 48 |
|
| 49 |
if form.validate_on_submit(): |
| 50 |
f = form.photo.data |
| 51 |
filename = secure_filename(f.filename) |
| 52 |
f.save(os.path.join( |
| 53 |
app.instance_path, 'photos', filename |
| 54 |
)) |
| 55 |
return redirect(url_for('index')) |
| 56 |
|
| 57 |
return render_template('upload.html', form=form) |
| 58 |
|
| 59 |
|
| 60 |
Similarly, you can use the :class:`MultipleFileField` provided by Flask-WTF |
| 61 |
to handle multiple files. It will check that the files is a list of non-empty instance of |
| 62 |
:class:`~werkzeug.datastructures.FileStorage`, otherwise ``data`` will be |
| 63 |
``None``. :: |
| 64 |
|
| 65 |
from flask_wtf import FlaskForm |
| 66 |
from flask_wtf.file import MultipleFileField, FileRequired |
| 67 |
from werkzeug.utils import secure_filename |
| 68 |
|
| 69 |
class PhotoForm(FlaskForm): |
| 70 |
photos = MultipleFileField(validators=[FileRequired()]) |
| 71 |
|
| 72 |
@app.route('/upload', methods=['GET', 'POST']) |
| 73 |
def upload(): |
| 74 |
form = PhotoForm() |
| 75 |
|
| 76 |
if form.validate_on_submit(): |
| 77 |
for f in form.photo.data: # form.photo.data return a list of FileStorage object |
| 78 |
filename = secure_filename(f.filename) |
| 79 |
f.save(os.path.join( |
| 80 |
app.instance_path, 'photos', filename |
| 81 |
)) |
| 82 |
return redirect(url_for('index')) |
| 83 |
|
| 84 |
return render_template('upload.html', form=form) |
| 85 |
|
| 86 |
|
| 87 |
Remember to set the ``enctype`` of the HTML form to |
| 88 |
``multipart/form-data``, otherwise ``request.files`` will be empty. |
| 89 |
|
| 90 |
.. sourcecode:: html |
| 91 |
|
| 92 |
<form method="POST" enctype="multipart/form-data"> |
| 93 |
... |
| 94 |
</form> |
| 95 |
|
| 96 |
Flask-WTF handles passing form data to the form for you. |
| 97 |
If you pass in the data explicitly, remember that ``request.form`` must |
| 98 |
be combined with ``request.files`` for the form to see the file data. :: |
| 99 |
|
| 100 |
form = PhotoForm() |
| 101 |
# is equivalent to: |
| 102 |
|
| 103 |
from flask import request |
| 104 |
from werkzeug.datastructures import CombinedMultiDict |
| 105 |
form = PhotoForm(CombinedMultiDict((request.files, request.form))) |
| 106 |
|
| 107 |
|
| 108 |
Validation |
| 109 |
~~~~~~~~~~ |
| 110 |
|
| 111 |
Flask-WTF supports validating file uploads with |
| 112 |
:class:`FileRequired`, :class:`FileAllowed`, and :class:`FileSize`. They |
| 113 |
can be used with both Flask-WTF's and WTForms's ``FileField`` and |
| 114 |
``MultipleFileField`` classes. |
| 115 |
|
| 116 |
:class:`FileAllowed` works well with Flask-Uploads. :: |
| 117 |
|
| 118 |
from flask_uploads import UploadSet, IMAGES |
| 119 |
from flask_wtf import FlaskForm |
| 120 |
from flask_wtf.file import FileField, FileAllowed, FileRequired |
| 121 |
|
| 122 |
images = UploadSet('images', IMAGES) |
| 123 |
|
| 124 |
class UploadForm(FlaskForm): |
| 125 |
upload = FileField('image', validators=[ |
| 126 |
FileRequired(), |
| 127 |
FileAllowed(images, 'Images only!') |
| 128 |
]) |
| 129 |
|
| 130 |
It can be used without Flask-Uploads by passing the extensions directly. :: |
| 131 |
|
| 132 |
class UploadForm(FlaskForm): |
| 133 |
upload = FileField('image', validators=[ |
| 134 |
FileRequired(), |
| 135 |
FileAllowed(['jpg', 'png'], 'Images only!') |
| 136 |
]) |
| 137 |
|
| 138 |
|
| 139 |
.. _recaptcha: |
| 140 |
|
| 141 |
Recaptcha |
| 142 |
--------- |
| 143 |
|
| 144 |
.. currentmodule:: flask_wtf.recaptcha |
| 145 |
|
| 146 |
Flask-WTF also provides Recaptcha support through a :class:`RecaptchaField`:: |
| 147 |
|
| 148 |
from flask_wtf import FlaskForm, RecaptchaField |
| 149 |
from wtforms import TextField |
| 150 |
|
| 151 |
class SignupForm(FlaskForm): |
| 152 |
username = TextField('Username') |
| 153 |
recaptcha = RecaptchaField() |
| 154 |
|
| 155 |
This comes with a number of configuration variables, some of which you have to configure. |
| 156 |
|
| 157 |
======================= ============================================== |
| 158 |
RECAPTCHA_PUBLIC_KEY **required** A public key. |
| 159 |
RECAPTCHA_PRIVATE_KEY **required** A private key. |
| 160 |
RECAPTCHA_API_SERVER **optional** Specify your Recaptcha API server. |
| 161 |
RECAPTCHA_PARAMETERS **optional** A dict of JavaScript (api.js) parameters. |
| 162 |
RECAPTCHA_DATA_ATTRS **optional** A dict of data attributes options. |
| 163 |
https://developers.google.com/recaptcha/docs/display#javascript_resource_apijs_parameters |
| 164 |
======================= ============================================== |
| 165 |
|
| 166 |
Example of RECAPTCHA_PARAMETERS, and RECAPTCHA_DATA_ATTRS:: |
| 167 |
|
| 168 |
RECAPTCHA_PARAMETERS = {'hl': 'zh', 'render': 'explicit'} |
| 169 |
RECAPTCHA_DATA_ATTRS = {'theme': 'dark'} |
| 170 |
|
| 171 |
For your convenience, when testing your application, if ``app.testing`` is ``True``, the recaptcha |
| 172 |
field will always be valid. |
| 173 |
|
| 174 |
In development environment or when you are offline you can disable all |
| 175 |
recaptcha fields:: |
| 176 |
|
| 177 |
RECAPTCHA_ENABLED = False |
| 178 |
|
| 179 |
If your site uses a nonce-based Content Security Policy, pass a ``nonce`` |
| 180 |
to :class:`RecaptchaField` so the generated ``<script>`` tag carries the |
| 181 |
matching ``nonce`` attribute. Because the nonce typically changes on every |
| 182 |
request, pass a zero-argument callable rather than a string so the value |
| 183 |
is resolved at render time:: |
| 184 |
|
| 185 |
from flask import g |
| 186 |
|
| 187 |
class SignupForm(FlaskForm): |
| 188 |
recaptcha = RecaptchaField(nonce=lambda: g.csp_nonce) |
| 189 |
|
| 190 |
And it can be easily setup in the templates: |
| 191 |
|
| 192 |
.. sourcecode:: html+jinja |
| 193 |
|
| 194 |
<form action="/" method="post"> |
| 195 |
{{ form.username }} |
| 196 |
{{ form.recaptcha }} |
| 197 |
</form> |
| 198 |
|
| 199 |
We have an example for you: `recaptcha@github`_. |
| 200 |
|
| 201 |
.. _`recaptcha@github`: https://github.com/pallets-eco/flask-wtf/tree/main/examples/recaptcha |