Issue
Stuck on user image input, everything works except picture, but I don't understand how to create picture object for flask_sqlalchemy, all the time shows me error. The idea is that user input all data and image and information will be available on home screen.
class Product(db.Model):
id = db.Column(db.Integer, primary_key=True) # auto +1
title = db.Column(db.String(20), nullable=False)
price = db.Column(db.Integer, nullable=False)
description = db.Column(db.Text)
status = db.Column(db.Boolean, default=True)
picture =???
And:
@app.route('/add_product', methods=['POST', 'GET'])
def create():
if request.method == 'POST':
title = request.form['title']
price = request.form['price']
description = request.form['description']
image = ?????
product = Product(title=title, price=price, description=description)
try:
db.session.add(product)
db.session.commit()
return redirect('/')
except:
return 'Error'
Solution
Your image should go somewhere on the filesystem, not the database. You can put it into your flask static directory and store path to it in the database. Your picture column will then become:
picture = db.Column(db.String(254), nullable=True)
And then you accept the image with something like this:
if request.method == 'POST':
title = request.form['title']
price = request.form['price']
description = request.form['description']
# accept uploaded image
uploaded = request.files.get('image')
if uploaded and uploaded.filename:
filename = secure_filename(uploaded.filename)
uploaded_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
uploaded.save(path)
image = uploaded_path
There are more examples in Flask docs: Uploading Files
Answered By - dmitrybelyakov
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.