python-3.x 在Flask中,我如何在文件py(而不是html)中写入条件并只打印html结果?

x8diyxa7  于 2023-06-25  发布在  Python
关注(0)|答案(1)|浏览(104)

我是Flask的新手。在index.html页面中,有一个combobox和一个textbox。如果我选择组合框的Red项,我希望文本框打印“You have selected the item Red”。

我想在python文件中实现这一点,而不是在html文件中。我看到条件也可以写在html文件中,但我不想把它们写在那里。因此,我想在app.py python文件中写入条件,并在index.html中写入NOT。就像这样:if colours.get() == "Red"。显然,然而,重要的是,我想在文本框index.html中显示输出
我怎样才能得到这个?谢谢大家!

** flask 代码:app.py

from flask import Flask, render_template

app = Flask(__name__)

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

@app.route("/combobox", methods=["GET","POST"])
def dropdown():
    colours = ["Red", "Blue", "Black", "Orange"]
    return render_template("index.html", colours=colours)

if __name__ == '__main__':
     app.run(host="0.0.0.0", port=8080)

**文本框和组合框代码:网站Map

<form name="Item_1" action="/getLigand" method="POST">
    <select name="colours">
      {% for colour in colours %}
     <option value="{{ colour }}" SELECTED>{{ colour }}</option>
      {% endfor %}     
   </select>
  </form>
  
<form action = "/result" method = "POST">
  <input type="text" name="result" />
  </form>
avwztpqn

avwztpqn1#

下面是一个有效的例子。app.py

from flask import Flask, render_template, request

app = Flask(__name__)

colours = ["Red", "Blue", "Black", "Orange"]

@app.route('/')
def index():
    return render_template("index.html", colours=colours, chosen="Black")

@app.route("/combobox", methods=["GET","POST"])
def dropdown():
    picked = request.form['colours']
    if picked == 'Red':
        message = "<<< You chose red"
    elif picked == 'Blue':
        message = "<<< You chose blue"
    elif picked == 'Black':
        message = "<<< You chose black"
    else:
        message = "<<< Oh no, you chose orange"

    return render_template("index.html", colours=colours, chosen=picked, message=message)

if __name__ == '__main__':
     app.run(host="127.0.0.1", port=8080)

这是templates/index.html

<form name="Item_1" action="/combobox" method="POST">
    <select name="colours">
      {% for colour in colours %}
        {% if colour == chosen %}
         <option value="{{ colour }}" SELECTED>{{ colour }}</option>
        {% else %}
         <option value="{{ colour }}">{{ colour }}</option>
        {% endif %}     
      {% endfor %}     
   </select>
   <input type="submit">
</form>
  
<form action = "/result" method = "POST">
  <input type="text" name="result" value="{{ message }}" />
</form>

后续

现在,写了所有这些,我开始想知道你是否希望消息显示,只要他们选择的颜色,而不必点击“提交”按钮。如果这就是你想要的,那是可以做到的,但这是一种非常不同的技术。这一切都必须在JavaScript中完成,作为您嵌入HTML中的代码。这一切都完全在浏览器内处理。它不会向Web服务器发送任何内容,因此不会涉及您的Python代码。

相关问题