Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError: 'FileField' object has no attribute 'File'

Tags:

python

flask

I'm new to Flask. I wanted to create a very basic site which allows to upload the images.I found the manual, however I wanted to make it slightly different. Here's my code:

###main.py

import os
from forms import UploadForm
from flask import Flask,render_template, url_for, redirect, send_from_directory
from werkzeug import secure_filename

ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

app = Flask(__name__)
app.config['SECRET_KEY'] = 'string'

@app.route('/', methods=('GET', 'POST'))
def upload():
    form = UploadForm()
    if form.validate_on_submit() and allowed_file(form.presentation.File.filename):
        filename = secure_filename(form.presentation.file.filename)

        print filename
        form.presentation.File.save(os.path.join('C:\Users\user\Desktop\New', filename))
    return redirect(url_for('/'))

    filename = None
    return render_template('upload.html', form=form, filename=filename)



if __name__ == '__main__':
    app.run(debug=True)

### forms.py   

from flask.ext.wtf import Form
from wtforms import FileField, validators, ValidationError, SubmitField
from wtforms.validators import InputRequired

class UploadForm(Form):
  presentation = FileField('Upload Image here', validators=[InputRequired()])
  submit = SubmitField("Send")


### upload.html
   {% for message in form.presentation.errors %}
     <div class="flash">{{ message }}</div>
   {% endfor %}
   <form action="/" method="POST" enctype="multipart/form-data">
     {{ form.presentation.label }}
     {{ form.presentation }}
     {{ form.csrf_token }}
     {{ form.submit}}
   </form>

On executing I get an error: AttributeError: 'FileField' object has no attribute 'File' I've searched the whole day, but I cannot find the answer what's wrong.

like image 563
user3085693 Avatar asked Sep 16 '25 21:09

user3085693


1 Answers

According to the wtforms doc FileField does not have File attribute that's right.

Here is the doc example:

class UploadForm(Form):
    image        = FileField(u'Image File', [validators.regexp(u'^[^/\\]\.jpg$')])
    description  = TextAreaField(u'Image Description')

    def validate_image(form, field):
        if field.data:
            field.data = re.sub(r'[^a-z0-9_.-]', '_', field.data)

def upload(request):
    form = UploadForm(request.POST)
    if form.image.data:
        image_data = request.FILES[form.image.name].read()
        open(os.path.join(UPLOAD_PATH, form.image.data), 'w').write(image_data)

As you can see the file is read from request.FILE not from the FileField. The FileField only has the attributes name and data.

like image 173
Benoît Latinier Avatar answered Sep 19 '25 09:09

Benoît Latinier