akdev
akdev

Reputation: 606

Attaching file to model with flask-admin

I'm using Flask-Admin to provide administrative interface to website. How can I handle file upload to sqlalchemy model, such as

class Product(db.Model):
    __tablename__ = 'products'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(5000))
    text_short = db.Column(db.String(3000))
    text = db.Column(db.String(50000))
    price = db.Column(db.Integer)
    image = db.Column(db.String(1000))

, where image is a field I want to store path to the image in /static directory?

Upvotes: 3

Views: 3812

Answers (1)

Joes
Joes

Reputation: 1818

Override on_model_change and do your upload logic there: http://flask-admin.readthedocs.org/en/latest/api/mod_model/#flask.ext.admin.model.BaseModelView.on_model_change

So, here's high level steps:

  1. Either contribute FileField to the form, or change type of the image field to FileField
  2. In on_model_change copy uploaded file to your static folder and update model image field with new file path

Hope it helps.

Upvotes: 6

Related Questions