【问题标题】:Can I use Python/Flask to compare 2 inputs in HTML?我可以使用 Python/Flask 比较 HTML 中的 2 个输入吗?
【发布时间】:2021-04-09 09:31:52
【问题描述】:

我在 HTML 中编写以下表单:

<form action="#" method="post">
  <input type="email" name="email"></input>
  <input type="email" name="email_conf"></input>
  <input type="submit" value = "Entrar"></input>
</form> 

由于我使用 Flask,我会使用 request.form('email')request.form('email_conf') 检索表单数据并比较函数返回的内容。

但我想知道是否可以在 .html 文件中使用 Python 通过执行类似操作来比较输入

<form action="#" method="post">
  <input type="email" name="email"></input>
  <input type="email" name="email_conf"></input>
  {% if email == email_conf %}
    <input type="submit" value = "Entrar"></input>
  {% endif %}

</form> 

感谢您的帮助!

【问题讨论】:

  • 基本上你想在用户点击提交按钮之前或之前进行比较?
  • 没错,我的错。单击提交按钮后,数据将被存储。点击后可以进行比较吗?感谢您的回复!
  • 如果您希望在客户端进行比较,最好只使用 javascript 进行比较。
  • @leoperessoli,我的意思是,您似乎已经在自己的示例中自己完成了。这:{% if email == email_conf %} 是您所要求的,将 2 值与 Python 的 Jinja 进行比较(没有 JavaScritp=
  • 如果这对您不起作用,那么您应该更好地说明您的期望以及为什么`{% if email == email_conf %}`没有按预期工作

标签: python html forms flask


【解决方案1】:

在能够进行“比较 2 个 HTML 表单”之前,您应该执行以下操作:

  1. 确保您要运行比较(或真正显示任何其他内容)用户单击提交按钮之后。因为 if is before then 这只能用 JavaScript 完成,但如果是 after 提交按钮然后转到第 2 步。

  2. 您需要将表单的状态从 Flask 的服务器“保存”回浏览器(服务器端 ---> 客户端)。我准备了一个简单的应用程序来向您展示:

1。将此添加到 app.py

​​>
from flask import Flask,request, render_template

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        print('here')
        email_1 = request.form['email']
        email_2 = request.form['email_conf']
        return render_template('index.html', email_1=email_1, email_2=email_2)
    return render_template('index.html')


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

2。将此添加到 template/index.html

注意:您在输入中有结束标签,不需要,因为输入是自动结束标签

<form action="/" method="POST">
      <input type="email" name="email">
      <input type="email" name="email_conf">

      <input type="submit" value = "Entrar">

    </form>
    <!--  Show the Output  -->
    {{email_1}} {{email_2}}

    <!--  Do wathever you want with that  -->
    {% if email_1 and email_2 %}
        {% if email_1 == email_2 %}
             <p>My email is {{email_1}} and I put the same as {{email_2}}</p>
        {% elif email_1 == 'eggs@spam.com'%}
            <p>{{email_1}} likes Python</p>
             {% for word in email_1 %}
                <option >{{word}}</option>
             {% endfor%}
        {% else %}
            <p>Something wrong with {{email_1}} maybe not match this-> {{email_2}}??</p>
        {% endif %}
    {% endif %}

文档

【讨论】:

    猜你喜欢
    • 2022-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多