使用wtforms的Flask-WTF文件上传未通过验证

时间:2018-11-09 08:50:52

标签: python flask wtforms

我正在尝试将文件上传到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(只需更改提交按钮,添加字段集标记即可,并且更改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表单中,因为该表单发布没有问题。我处理文件导入表格不正确吗?

2 个答案:

答案 0 :(得分:0)

最后将其修复。将表单更改为...

{% 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 %}

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

答案 1 :(得分:-1)

根据建议here,解决方案是更改:
form = UploadFileForm(request.form)
到:
form = UploadFileForm()