Flask_admin自定义保存数据

管理后台自定义保存数据

  1. 由于使用Flask-admin在上传图片的时候,不能使用中文命名的图片

  2. 自己写一个ModelView,并且重写create_model方法

    from flask import current_app, flash
    from flask_admin.contrib.sqla import ModelView
    from flask_admin.babel import gettext
    from sqlalchemy.orm.base import instance_state
    import logging
    from uuid import uuid1
    
    log = logging.getLogger("flask-admin.sqla")
    
    
    class MyModelView(ModelView):
    
        def create_model(self, form):
            """
                Create model from form.
    
                :param form:
                    Form instance
            """
            try:
                model = self._manager.new_instance()
                # TODO: We need a better way to create model instances and stay compatible with
                # SQLAlchemy __init__() behavior
                state = instance_state(model)
                self._manager.dispatch.init(state, [], {})
                try:
                    image = form.main_image.data.filename
                    img_format = image[image.rfind('.') + 1:]
                    if img_format not in current_app.config['IMG_FORMAT']:
                        flash(gettext('图片不合法', error=str('图片不合法')), 'error')
                        self.session.rollback()
                        return False
                    form.main_image.data.filename = str(uuid1()) + '.' + img_format
                except Exception as e:
                    pass
                form.populate_obj(model)
                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
    
    
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 数字50 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读