【问题标题】:Passing a jinja variable to backend将 jinja 变量传递给后端
【发布时间】:2022-01-13 11:24:24
【问题描述】:

单击相应按钮时,我正在尝试将 for 循环中生成的 jinja 变量传递给后端。当我单击任何按钮时,列表中的第一个值被传递。我试过的代码是

代码

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/search_tag', methods=["GET", "POST"])
def search_tag():
    if request.method == 'POST':
        print("hi")
        tag_x = request.form['rawtext']
        print(tag_x)
        return render_template('index.html', messg = "SUCCESS")
    else:
        return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)

HTML 代码

<!DOCTYPE html>
<html>
<head>
    <title>Test App</title>
</head>
<body>

<form method="POST" action="{{ url_for('search_tag')}}">
  <div id ="result">
    <p style="color:red">
      {% for i in ["hello","hi","travel","goal"] %}
            <li>{{ i }}
            <input type="hidden" id="rawtext" name="rawtext" value="{{ i }}">
            <input type="submit" name="submit" value="click" class="btn btn-info">
            </li>
        {% endfor %}
    </p><br>
  </div>
</form>
{{ messg }}
</body>
</html>

</body>
</html>

提前致谢

【问题讨论】:

    标签: python html flask jinja2


    【解决方案1】:

    在你的 html 中做这样的事情:

    <input type="hidden" id="rawtext" name="rawtext{{loop.index}}" value="{{ i }}">
    

    您还需要在烧瓶代码中使用 for 循环来遍历所有名称。

    @app.route('/search_tag', methods=["GET", "POST"])
    def search_tag():
        if request.method == 'POST':
            print("hi")
            for i in ["hello","hi","travel","goal"]:
               tag_x = request.form[i]
               print(tag_x)
            return render_template('index.html', messg = "SUCCESS")
    

    【讨论】:

    • 感谢您的回复。但它不是数字。它可以是字符串。我以数字为例。更新了html代码。表单关闭时出现 1 个错误。现在更正了。现在即使我点击任何按钮,也只有第一个值通过
    • 那是因为所有输入的名称都相同。您还应该注意更改名称以捕获所有单独的输入。我将编辑我的答案。
    • 感谢您的回复。你能发帖给我看看烧瓶边是怎么做的吗?有点糊涂。提前致谢
    【解决方案2】:

    我通过使用单选按钮和@Ioannis Skaltsas 的建议解决了(感谢您的建议。如果有更好的方法,请建议像 ajax 或其他东西).. 更正的代码是 --->

    <!DOCTYPE html>
    <html>
    <head>
        <title>Test App</title>
    </head>
    <body>
    
    <form method="POST" action="{{ url_for('search_tag')}}">
      <div id ="result">
        <p style="color:red">
          {% for i in ["hello","hi","travel","goal"] %}               
                <input type="radio" id="rawtext" name="rawtext" value="{{ loop.index }}">{{ i }} <br>
            {% endfor %}
         <input type="submit" name="submit" value="click" class="btn btn-info">
        </p><br>
      </div>
    </form>
    {{ messg }}
    </body>
    </html>
    
    </body>
    </html>
    

    由于最初list是在python代码中生成的(这里静态使用在html代码中),基于使用按钮提交的选定循环索引,我可以在python结束时从list中获取值。

    【讨论】:

      猜你喜欢
      • 2019-01-02
      • 1970-01-01
      • 2023-01-29
      • 1970-01-01
      • 1970-01-01
      • 2019-12-07
      • 2014-11-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多