首页 > 解决方案 > WTForms HiddenField() POST 后不包含任何数据

问题描述

我对 Flask 和 WTForms 很陌生,但我想做的是为用户提供一个按钮,让他们自动将 GIF 上传到 giphy.com。GIF 位于服务器上,并在 generate.html 上呈现给他们的浏览器。GIF 下面是一个提交按钮,我打算启动一个 app.route 来处理上传过程(打开一个新选项卡,一旦该过程完成,最终将显示一个指向已上传 GIF 的链接)。

问题:用于上传 gif(单击提交按钮)的 app.route 没有分配给其 HiddenField (gifLocation) 的数据,尽管我认为我在加载 generate.html 时分配了它。

我的 FileLocationForm 代码:

# class for sending along a file path used for uploading a gif
class FileLocationForm(FlaskForm):
    gifLocation = HiddenField()
    submit = SubmitField('Upload to GIPHY')

首次在我的服务器上创建 GIF 时,我运行以下命令(在 app.route 中用于 generate.html):

form = FileLocationForm(gifLocation=gif_outfileloc)
return render_template('generate.html', gif_outfileloc=gif_outfileloc[7:], form=form)

此时, gif_outfileloc 存在并且 100% 指向我服务器上的有效 GIF。第二个参数的格式是因为我在“静态”文件夹中显示一个文件,并且需要从路径中删除“静态”,因为它是由烧瓶在 img 标签中添加的。那部分正在工作。

generate.html 的代码:

{% extends 'layout.html' %}
{% block content %}
<div class="gif_display center-align">
    <img class="img-fluid mx-auto my-auto d-block" width="480" height="360" src={{ url_for("static", filename = gif_outfileloc) }}>   
</div>
<form id='uploadGifForm' action = {{ url_for('generateGIFpage') }} target = '_blank' method='POST'>
    {{ form.gifLocation() }}
    {{ form.submit() }}
</form>
{% endblock content %}

我们在页面上获得了一个提交按钮,单击它确实会打开一个新选项卡,但它会将我们带回家,而不是上传到 giphy。

生成GIF页面的代码:

@app.route("/upload", methods=["GET", "POST"])
def generateGIFpage():
    if request.method == 'POST':
        if request.form.get('gifLocation'):
            gifLocation = request.form.get('gifLocation')
            giphyobj = Giphy(API_KEY)
            # response (below) is the URL for our giphy upload
            response = giphyobj.upload([], gifLocation, username="QuoteGIFr")
            return render_template('upload.html', response = response)
    return redirect(url_for('homepage'))

任何帮助表示赞赏。我已经尝试了一些变化,但我还没有取得任何成功。如果您需要更多代码来理解我在做什么,或者需要更多关于我正在尝试做什么的信息,请询问。

标签: python-3.xflask-wtformshidden-field

解决方案


推荐阅读