使用flask-admin将文件附加到模型 [英] Attaching file to model with flask-admin

查看:466
本文介绍了使用flask-admin将文件附加到模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Flask-Admin为网站提供管理界面。如何处理文件上传到sqlalchemy模型,如$ / $>

  class Product(db.Model):
__tablename__ = 'product'
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)$ b $ image = db.Column(db.String( 1000))

,其中 image 是字段我想在 / static 目录中存储图像的路径?

解决方案

覆盖 on_model_change 并在那里执行上传逻辑: http://flask-admin.readthedocs.org/en/latest/api/mod_model/#flask.ext.admin.model.BaseModelView.on_model_change



所以,这是高层次的步骤:


  1. 将FileField添加到表单中,或将图像字段的类型更改为FileField

  2. on_model_change 将上传的文件复制到您的静态文件夹,并使用新的文件路径更新模型图像字段

希望有帮助。


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?

解决方案

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.

这篇关于使用flask-admin将文件附加到模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆