0

I am new to python and programming in general.

I keep getting UploadNotAllowed error even though I set the form field validator to Optional(). My goal is to allow users the choice of uploading or not uploading a profile picture. All configurations work well when an image if selected to be uploaded. Any help will be appreciated.

Here is the form field:

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

Here is my views.py:

if form.validate_on_submit():
    filename = images.save(request.files['profile_pic'])
    current_user.profile_pic = images.url(filename)
Alex M
  • 2,756
  • 7
  • 29
  • 35
aharding378
  • 207
  • 1
  • 3
  • 16

1 Answers1

0

this is a slightly edited version from the docs (here). Which also give you some reminders about what your html file should contain.

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
  • 155
  • 7
  • Thanks for your answer @smundlay. This is not working for me, I am getting this error: AttributeError: 'NoneType' object has no attribute 'filename'. My guess would be because of the f.filename? – aharding378 Sep 20 '17 at 02:06