Reputation: 465
I have a form contains name and pictures
MyForm:
name = TextField(
u'name',
validators=[
validators.DataRequired(),
validators.Length(min=1, max=25)
]
)
pictures = FileField(
u'pictures',
validators=[
FileRequired(),
FileAllowed(['jpg', 'png'], 'Images only!')
]
)
Jinja2 template:
{% from "_form_helpers.tpl" import render_field %}
<form method="post" action="" enctype="multipart/form-data">
<dl>
{{ render_field(form.name) }}
{{ render_field(form.pictures) }}
</dl>
<p>{{ form.submit }}
</form>
I want to upload one or more picture in a single field (Multi selection).
How to do this?
Thanks..
Upvotes: 7
Views: 7162
Reputation: 141
Since version 2.2 wtforms supports MultipleFileField
. (From https://wtforms.readthedocs.io/en/stable/changes.html#version-2-2)
Upvotes: 2
Reputation: 7674
From: http://wtforms.readthedocs.org/en/latest/fields.html
render_kw (dict) – If provided, a dictionary which provides default keywords that will be given to the widget at render time.
Therefore, you can pass {multiple: True}
to the field definition as below:
forms.py
class UploadImages(Form):
imgs = FileField(
'Select images',
render_kw={'multiple': True},
)
upload = SubmitField('Upload')
uploade_template.html
{% import "bootstrap/wtf.html" as wtf %}
{{ wtf.quick_form(form) }}
Upvotes: 5
Reputation: 4151
You need to specify the multiple attribute for the input tag. This can be done in your templates like so:
form.pictures(multiple="")
which will result in your generated html allowing for multiple file selection:
<input id="pictures" multiple name="pictures" type="file">
images = request.files.getlist("pictures")
if images:
for img in images:
# Create Images
file_name = str(uuid.uuid4()) + secure_filename(img.filename)
image_file = os.path.join(app.config['UPLOAD_FOLDER'], file_name)
img.save(image_file)
# Save record
image = models.Image(record_id=record.record_id,
file_name=file_name.encode('utf-8'))
db.session.add(image)
db.session.commit()
Upvotes: 9