Flask WTF上传文件错误

时间:2017-03-16 19:18:44

标签: python flask-wtforms

我在尝试使用Flask上传文件时收到错误'NoneType' object has no attribute 'filename'

我跟随documentation,但我无法让它发挥作用。

class SubmitLocations(Form):
    title = TextField("Name Of Location (What do the locals call it)")
    description = TextField("Please describe the location")
    upload = FileField("Please select an image to upload")


@app.route('/add_spot/', methods=["GET","POST"])
@login_required
def add_spot():
    try:
        form = SubmitLocations(request.form)

        if request.method == "POST":
            title = form.title.data
            description = form.description.data
            f = form.upload.data
            filename = secure_filename(f.filename)
            f.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

这是我的HTML表单

  <form method=post enctype="multipart/form-data" action="/add_spot/">
    <dl>
      {{render_field(form.title)}}
      {{render_field(form.description)}}
      {{render_field(form.upload)}}
    </dl>
    <p><input type=submit value=Submit></p>
  </form>

页面渲染得很好,我可以选择要上传的文件,但是当我提交时,我会收到上面提到的错误'NoneType' object has no attribute 'filename'我想知道是否有人可以指出我的错误?也许我遗漏了一个关键的一块?

需要注意的是,如果删除文件上传部分,我可以提交此表单而不会出现任何错误。

1 个答案:

答案 0 :(得分:1)

好像你提交了没有文件的表单。您需要先验证表单。如果您依赖于拥有该文件,请将FileRequired添加到验证器。

from flask_wtf.file import FileRequired


class SubmitLocations(Form):
    # ...
    upload = FileField("Please select an image to upload", validators=[FileRequired()])


def add_spot():
    form = SubmitLocations(request.form)

    # changed this line
    if form.validate_on_submit():  
        title = form.title.data
        description = form.description.data
        f = form.upload.data
        filename = secure_filename(f.filename)
        f.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))