python - Flask发送html数据回 View

标签 python post flask request jinja2

我正在创建一个页面,其中包含由 jinja for 循环创建的列表。 我希望用户在该列表中选择一个项目。 我希望该选择将用户发送到该项目页面,并将所选项目发送回我的 python 代码以进行进一步处理。

在我的“home.html”页面中,我有以下内容:

{% for item in list %}
    {{ item }}
    <form method='POST'>
        <input type='submit' value='select'>
    </form>
{% endfor %}

然后在我的 python View 中:

@app.route('/', methods=['GET','POST'])
def home():
    list = ['a','b','c']

    #???????????????????????????????????????????????
    selected = request.form.item

    return render_template('home.html', list=list)

最佳答案

您需要在 home() 路由中分别处理 GETPOST 方法。像这样的事情:

@app.route('/', methods=['GET','POST'])
def home():
    if request.method == 'POST':
        selected = request.form.item
        # on this line you can process the selected item, but you haven't
        # stated how you'll do that, so I don't know what to display here
        return redirect(url_for('item_page.html', item=selected))
    else:
        list = ['a','b','c']
        return render_template('home.html', list=list)

显然,我还假设您有一个模板 item_page.html,用于显示用户选择的单个项目。如果没有,请替换您将在那里使用的任何模板。您还需要一个 @app.route 来处理该模板。

关于python - Flask发送html数据回 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42490591/

相关文章:

python - 对 linux 服务器的 ajax 请求有时会返回答案,有时会返回错误 500

python - 将python日期时间插入mysql表

python - 为nodejs安装mongoose模块时出错

python - iOS+GoogleChrome 上的“内容处置”[Google App Engine 上的 Flask]

java - 在Java中发布XML并获取响应代码

$_FILES 的 PHP 过滤输入数组?

django - 使用中间件限制对外键的选择

python - 如何将 Google-Cloud-Vision OCR protobuf 响应保存/加载到磁盘?

python - 当 MySQL Select 语句时,Flask 出现 Python 错误

javascript - 使用 JSON 将 Javascript 对象发送到 Python Flask 时出错