Wtforms, Multi selection file upload
Asked Answered
H

3

7

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..

Hashum answered 17/5, 2014 at 0:23 Comment(0)
S
9

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">

How to Manipulate multiple files using request.files:

    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()
Silden answered 2/4, 2015 at 0:27 Comment(2)
That lets you select multiple, but with something like request.files, you only get one key this way through WTF. Can you elaborate on how you are manipulating this on the back end?Jepum
I have added a code snippet from an old project that may answer your question.Silden
L
5

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) }}
Latanya answered 5/4, 2016 at 2:47 Comment(0)
G
2

Since version 2.2 wtforms supports MultipleFileField. (From https://wtforms.readthedocs.io/en/stable/changes.html#version-2-2)

Goldin answered 5/12, 2018 at 17:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.