【问题标题】:With Flask-Admin and Flask how can I submit a form\view based on ModelView from code?使用 Flask-Admin 和 Flask 如何从代码中提交基于 ModelView 的表单\视图?
【发布时间】:2019-08-31 17:53:58
【问题描述】:

使用 Flask-Admin 和 Flask 如何从代码中提交基于 ModelView 的表单\视图?

我正在尝试创建一个单独的视图\表单,允许用户在一个表单中添加多个条目。特别允许上传多个具有通用前缀名称和通用参数的图像。我想通过从代码中提交单张图片上传表单来做到这一点,因为它会做一些额外的处理,比如调整图片大小,我想让 Flask-Admin 处理连接数据库条目和文件。

这是我想通过代码提交的表单:

class ImageView(ModelView):
    def _list_thumbnail(view, context, model, name):
        if not model.path:
            return ''

        return Markup('<img src="%s">' % url_for('media',
                                                 filename=form.thumbgen_filename(model.path)))

    column_labels = dict(show_in_header="Show In Header?",
                         path="Image")

    form_create_rules = ("name",
                         "tags",
                         rules.Text(
                             "Use this image as header. If more than one image is selected header image will be random each time the page is loaded."),
                         "show_in_header",
                         "path")
    form_excluded_columns = ("timestamp")

    column_formatters = {
        'path': _list_thumbnail
    }

    thumbnail_size = config("media", "thumbnail_size")

    form_extra_fields = {
        'path': BroImageUploadField('Image',
                                    base_path=IMAGES_FOLDER,
                                    thumbnail_size=(thumbnail_size, thumbnail_size, True),
                                    endpoint="media",
                                    url_relative_path='media',
                                    relative_path=None)
    }

    def is_accessible(self):
        return current_user.is_authenticated

    def inaccessible_callback(self, name, **kwargs):
        # redirect to login page if user doesn't have access
        return redirect(url_for('login', next=request.url))

在这里我正在创建一个表单,但我不确定.process() 是提交它的函数吗?有吗?

lass MultipleImagesUploadView(BaseView):
    @expose("/", methods=["GET", "POST"])
    def index(self):
        if request.method == "POST":
            a_form = MultipleImagesForm(request.form)
            base_name = a_form.base_name.data
            tags = a_form.tags.data
            show_in_header = a_form.show_in_header.data
            print (request.files.getlist(a_form.images.name))
            uploaded_files = request.files.getlist(a_form.images.name)
            for i, uf in enumerate(uploaded_files):
                try:
                    name, ext = os.path.splitext(uf.filename)
                    if ext not in IMAGE_EXTENSIONS:
                        flash("Image file {} was skipped as it's extension is not supported ({}).".format(uf.filename, ext), category="warning")
                        continue
                    image_contents = uf.stream.read()
                    image_form = ImageView()
                    image_form.name.data = "{}_{}".format(base_name, i)
                    image_form.tags.data = tags
                    image_form.show_in_header.data = show_in_header
                    image_form.path.data = image_contents
                    image_form.process()
                except Exception as e:
                    flash ("Unhandled exception: {}".format(e), category="warning")
            flash("Images were added to the gallery.", category='success')

        a_form = MultipleImagesForm()
        print("############", a_form)
        return self.render('/admin/multiple_images_upload.html', form=a_form)

我想不出一种通过代码提交表单的方法,一直试图在文档和谷歌中找到答案几个小时,但没有运气。

【问题讨论】:

    标签: python flask wtforms flask-admin


    【解决方案1】:

    发现问题。就我而言,我错过了enctype="multipart/form-data"。如果没有该文件,部分将作为空发送。

    也改为使用from flask_wtf import FlaskForm,并在模板中启用{{ form.files(class="form-control", multiple="") }}

    然后可以在 POST 请求中使用 uploaded_files = request.files.getlist("files") 访问文件,它将保存文件对象数组。

    我希望这对某人有所帮助。如果需要任何其他格式,我将添加或扩展答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-21
      • 1970-01-01
      相关资源
      最近更新 更多