简体   繁体   English

使用flask-admin将文件附加到模型

[英]Attaching file to model with flask-admin

I'm using Flask-Admin to provide administrative interface to website. 我正在使用Flask-Admin提供网站的管理界面。 How can I handle file upload to sqlalchemy model, such as 如何处理文件上传到sqlalchemy模型,例如

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? ,其中image是我要在/static目录中存储图像路径的字段?

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 覆盖on_model_change并在那里执行上传逻辑: http : 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 将FileField贡献给表单,或将图像字段的类型更改为FileField
  2. In on_model_change copy uploaded file to your static folder and update model image field with new file path on_model_change将上传的文件复制到您的静态文件夹中,并使用新文件路径更新模型image字段

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM