如何让 Flask-admin 面板使用模型的 init 方法?

How can I make the Flask-admin panel use the init method of the model?

当我通过 Flask 管理面板添加新集合时,我没有得到 init 方法来通过另一个函数缩小图像。当我通过 Python 控制台添加新集合时,一切正常。但是 Flask 管理面板...

型号:

class Collections(db.Model):
    __tablename__ = 'collections'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False)
    preview_photo = db.Column(db.String, nullable=False)

    def __init__(self, name, preview_photo):
        self.name = name
        self.preview_photo = collections_resize(preview_photo)

    def __repr__(self):
        return f'{self.name}' 

如您所见,在 init 方法中我传入 self.thumb_photo collections_resize() 函数的结果。但是这个方法没有通过面板运行,能解释一下为什么吗?

查看模型:

class CollectionsView(ModelView):
    form_columns = ['name', 'preview_photo']

admin.add_view(CollectionsView(Collections, db.session))

我最终以这种方式重写了视图模型并且它起作用了,但我不得不为它编写一个单独的 html 它看起来很奇怪,但它会起作用。如果您有更好的想法,请提出来。

class CollectionsView(ModelView):
    form_columns = ['id', 'name', 'preview_photo']

    @expose('/new/', methods=('GET', 'POST'))
    def create_view(self):
        if request.method == 'POST':
            if 'file' not in request.files:
                return redirect(request.url)

            file = request.files['file']

            if file.filename == '':
                return redirect(request.url)

            if file and allowed_file(file.filename):
                filename = file.filename
                file.save(os.path.join('path', filename))
                name = request.form.get('name')
                preview_photo = filename
                q = Collections(name=name, preview_photo=preview_photo)
                db.session.add(q)
                db.session.commit()
                return redirect('/admin/collections')

        return render_template('create_coll.html')

覆盖 create_model.

class CollectionsView(ModelView):
    form_columns = ['name', 'preview_photo']

    def build_new_instance_and_populate_obj(form):
        name = form.get('name')
        preview_photo = form.get('preview_photo')
        return Collections(name=name, preview_photo=preview_photo)

    def create_model(self, form):
        try:
            # model = self.build_new_instance()
            # form.populate_obj(model)
            model = self.build_new_instance_and_populate_obj(form)

            self.session.add(model)
            self._on_model_change(form, model, True)
            self.session.commit()
        except Exception as ex:
            if not self.handle_view_exception(ex):
                flash(gettext('Failed to create record. %(error)s', error=str(ex)), 'error')
                log.exception('Failed to create record.')

            self.session.rollback()

            return False
        else:
            self.after_model_change(form, model, True)

        return model

参考:flask-admin/flask-admin#1927