Wtforms, multiscreen file download

I have a form containing a name and images

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 images in one field (Multi selection).

How to do it?

Thank..

+4
source share
3 answers

You need to specify a multiple attribute for the input tag. This can be done in your templates:

form.pictures(multiple="")

which will lead to the creation of the generated html, allowing you to select multiple files:

<input id="pictures" multiple name="pictures" type="file">

How to manipulate multiple files with 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()
+6
source

From: http://wtforms.readthedocs.org/en/latest/fields.html

render_kw (dict) - , , , .

, {multiple: True} , :

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) }}
+4

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

0
source

Source: https://habr.com/ru/post/1540923/


All Articles