【问题标题】:Flask-uploads - I keep getting UploadNotAllowed errorFlask-uploads - 我不断收到 UploadNotAllowed 错误
【发布时间】:2017-09-19 08:43:24
【问题描述】:

我是 python 和一般编程的新手。

即使我将表单字段验证器设置为Optional(),我仍不断收到UploadNotAllowed 错误。我的目标是允许用户选择上传或不上传个人资料图片。如果选择上传图像,所有配置都可以正常工作。 任何帮助将不胜感激。

这是表单域:

class SettingsForm(FlaskForm):
        profile_pic = FileField('Profile Picture', validators= [Optional(), FileAllowed(images, 'Only images are allowed here')])

这是我的views.py:

if form.validate_on_submit():
    filename = images.save(request.files['profile_pic'])
    current_user.profile_pic = images.url(filename)

【问题讨论】:

    标签: python flask-wtforms flask-uploads


    【解决方案1】:

    这是文档 (here) 中经过略微编辑的版本。这也给你一些关于你的 html 文件应该包含什么的提醒。

    from flask_wtf import FlaskForm
    from flask_wtf.file import FileField, FileRequired
    from werkzeug.utils import secure_filename
    
    class PhotoForm(FlaskForm):
        photo = FileField(validators=[Optional(), FileAllowed(images, 'Only images are allowed here')])
    
    @app.route('/upload', methods=['GET', 'POST'])
    def upload():
        if form.validate_on_submit():
            f = form.photo.data
            filename = secure_filename(f.filename)
            #you can replace this with wherever you want to save your images            
            f.save(os.path.join(
                    app.instance_path, 'photos', filename
                ))
            current_user.profile_pic = images.url(filename)
            return redirect(url_for('index'))
    
        return render_template('upload.html', form=form)
    

    【讨论】:

    • 感谢您的回答@smundlay。这对我不起作用,我收到此错误:AttributeError: 'NoneType' object has no attribute 'filename'。我的猜测是因为 f.filename?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-26
    • 2016-02-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-10
    • 2021-11-06
    相关资源
    最近更新 更多