【问题标题】:Flask-Admin column_formatters not calledFlask-Admin column_formatters 未调用
【发布时间】:2022-01-20 07:33:41
【问题描述】:

我正在使用 Flask-Admin 并想在我的内联模型视图中添加一个额外的字段。 目的是显示文件系统中的图像。

问题是我的列格式化程序永远不会被调用并且图像永远不会被加载。任何建议将不胜感激。

class ImageView(ModelView):
    form_columns = ['id', 'mime_type', 'path']

    @staticmethod
    def _user_formatter(view, context, model, name):
        logging.warning("NOT CALLED")
        return Markup('<img src="%s">' % form.thumbgen_filename(1))

    column_formatters = dict(path=lambda v, c, m, p: ImageView._user_formatter(v, c, m, p))

    form_extra_fields = {
        'path': form.ImageUploadField('Image', base_path='/app/uploads', thumbnail_size=(400, 400, True))
    }

class VehicleModelView(ModelView):
    inline_models = [ImageView(DbModel, db.session)]

【问题讨论】:

    标签: python python-3.x flask flask-sqlalchemy flask-admin


    【解决方案1】:

    尝试在不使用@staticmethod 的情况下调用它

    flask-admin 就是这么称呼它的 column_formatters

    class ImageView(ModelView):
        form_columns = ['id', 'mime_type', 'path']
    
        def _user_formatter(view, context, model, name):
            logging.warning("NOT CALLED")
            return Markup('<img src="%s">' % form.thumbgen_filename(1))
    
        column_formatters = dict(path=_user_formatter)
    
        form_extra_fields = {
            'path': form.ImageUploadField('Image', base_path='/app/uploads', thumbnail_size=(400, 400, True))
        }
    

    这是 Flask-Admin 给出的示例

    class ImageView(sqla.ModelView):
        def _list_thumbnail(view, context, model, name):
            if not model.path:
                return ''
    
            return Markup('<img src="%s">' % url_for('static',
                                                     filename=form.thumbgen_filename(model.path)))
    
        column_formatters = {
            'path': _list_thumbnail
        }
    
        # Alternative way to contribute field is to override it completely.
        # In this case, Flask-Admin won't attempt to merge various parameters for the field.
        form_extra_fields = {
            'path': form.ImageUploadField('Image',
                                          base_path=file_path,
                                          thumbnail_size=(100, 100, True))
        }
    

    【讨论】:

    • 问题是我正在为编辑视图尝试这个。根据文档,此视图不调用 column_formatters。 :-(
    • 您的视图被扩展到 ModelView,它也使用 BaseModelView 中的 edit_view。
    猜你喜欢
    • 1970-01-01
    • 2019-08-15
    • 2022-01-18
    • 2012-08-02
    • 2017-05-28
    • 1970-01-01
    • 2014-03-24
    • 2019-09-17
    • 1970-01-01
    相关资源
    最近更新 更多