【问题标题】:Flask-WTF File Upload with wtforms not passing validation带有未通过验证的 wtforms 的 Flask-WTF 文件上传
【发布时间】:2018-11-09 08:50:51
【问题描述】:

我正在尝试将文件上传到 Flask 表单,但无法通过验证。我一直在关注docs,并尝试了这种当前方法和CombinedMultiDict() 提交到表单中,但没有成功。我已经打印出错误是..

print(form.validate_on_submit())
False
print(form.errors)
{'upload': ['This field is required.']}

进口..

import os
from flask import Flask, render_template, request, flash, redirect, url_for, session, logging
from flask_mysqldb import MySQL
from wtforms import Form, SelectField, StringField, TextAreaField, PasswordField, BooleanField,validators
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileRequired, FileAllowed
from werkzeug.utils import secure_filename

这是我的表格..

class UploadFileForm(FlaskForm):
    file_name = StringField('File Title', [
        validators.Length(min=4, max=35, message="File Title must be between 4 & 35 characters."),
        validators.Regexp(username_reg, message="File Title can contain only letters, numbers or underscores.")
    ])
    file_desc = TextAreaField('Body', [
        validators.Length(max=500),
        validators.Regexp(group_reg, message="The description can only contain letters, numbers, underscores, dashes, exclaimation/question marks, or periods."),
        validators.Optional()
    ])
    upload = FileField('File', validators=[FileRequired()])

我的看法...

@app.route('/upload_file', methods=['GET', 'POST'])
def upload_file():
    form = UploadFileForm():
    if form.validate_on_submit(): 
        print('========================')
        # file_name = secure_filename(form.file.data)
        file_name = form.file_name.data
        file_desc = form.file_desc.data
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(form.upload.data.filename))
        form.upload.data.save(file_path)

        # Get user and group
        user = User.query.filter_by(username=session.get('username')).first()
        group = Group.query.filter_by(groupname=session.get('groupname')).first()

        # Add to DB
        new_file = File(file_name=file_name, file_desc=file_desc, file_path=file_path, uploader=user.username, user=user, group=group)
        db.session.add(new_file)
        db.session.commit()

        flash('File Uploaded!')
        return redirect(url_for('dashboard'))
    return render_template('upload_file.html', form=form)

HTML 页面...

{% extends 'layout.html'%}

{% block body %}
    <h1>Upload File</h1>
    {% from "includes/_formhelpers.html" import render_field %}
    <form method="POST" action="" enctype="multipart/form-data">
        {{ form.csrf_token }}
        <div class="form-group">
        {{render_field(form.file_name, class_="form-control")}}
        </div>
        <div class="form-group">
        {{render_field(form.file_desc, class_="form-control")}}
        </div>
        <div class="form-group">
        {{render_field(form.upload, class_="form-control")}}
        </div>
        <input type="submit" class="btn btn-primary" value="Submit">
    </form>
{% endblock %}

当我提交文件时,它会忽略提交的文件,这会导致验证失败。我是验证错了,还是搞砸了表格?

提前致谢!

--更新--
仍在为空白文件问题而苦苦挣扎。我对表单和 html 进行了一些尝试,但提交表单时仍然没有收到任何输入。

新表单(只是稍微更改了上传字段并添加了表单提交)...

class UploadFileForm(FlaskForm):
    file_name = StringField('File Title', [
        validators.Length(min=4, max=35, message="File Title must be between 4 & 35 characters."),
        validators.Regexp(username_reg, message="File Title can contain only letters, numbers or underscores.")
    ])
    file_desc = TextAreaField('Body', [
        validators.Length(max=500),
        validators.Regexp(group_reg, message="The description can only contain letters, numbers, underscores, dashes, exclaimation/question marks, or periods."),
        validators.Optional()
    ])
    upload = FileField('File', validators=[FileRequired(), FileAllowed(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'ppt'], 'Invalid File Type. Must be .txt, .pdf, .png, .jpeg')])
    submit = SubmitField('Post')

新的HTML(刚改了提交按钮,无奈之下加了fieldset标签,还改了form.upload输入)...

<h1>Upload File</h1>
    {% from "includes/_formhelpers.html" import render_field %}
    <form method="POST" action="" enctype=“multipart/form-data”>
        {{ form.csrf_token }}
        <fieldset class="form-group">
            <div class="form-group">
                {{render_field(form.file_name, class_="form-control")}}
                </div>
                <div class="form-group">
                {{render_field(form.file_desc, class_="form-control")}}
                </div>
                <div class="form-group">
                {{ form.upload(class="form-control-file") }}
                </div>
        </fieldset>
        <div class="form-group">
            {{ form.submit(class="btn btn-primary") }}
        </div>
    </form>

视图没有改变。我似乎问题集中在 html 表单中,因为表单发布没有问题。我处理文件导入表单是否错误?

【问题讨论】:

    标签: python flask wtforms


    【解决方案1】:

    终于修好了。将表格更改为...

    {% block body %}
        <h1>Upload File</h1>
        {% from "includes/_formhelpers.html" import render_field %}
        <form method="POST" action="" enctype="multipart/form-data">
            {{ form.hidden_tag() }}
            <fieldset class="form-group">
                <div class="form-group">
                    {{render_field(form.file_name, class_="form-control")}}
                </div>
                <div class="form-group">
                    {{render_field(form.file_desc, class_="form-control")}}
                </div>
                <div class="form-group">
                    {{ form.upload.label() }}
                    {{ form.upload(class="form-control-file") }}
                </div>
            </fieldset>
            <div class="form-group">
                {{ form.submit(class="btn btn-outline-info") }}
            </div>
        </form>
    {% endblock %}
    

    还调整了一些其他的导入内容。

    【讨论】:

    • 我正在为同样的事情苦苦挣扎。您能否分享有关您如何解决它的更多详细信息?提供的代码不会改变任何东西(至少它在我这边不起作用)。提前致谢!
    • 这是不久前的事了,但据我所知,我不得不从使用 csrf_token 切换到 hidden_​​tag() 并允许我访问该文件。我知道这有点晚了,但如果你也修好了,请告诉我。
    【解决方案2】:

    按照here的建议,解决办法是改:
    form = UploadFileForm(request.form)
    至:
    form = UploadFileForm()

    【讨论】:

    • 这可能是个问题,但不是我遇到的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多