【问题标题】:Not getting attributes from form elements没有从表单元素中获取属性
【发布时间】:2018-06-25 16:22:23
【问题描述】:

我有一个 Flask 应用程序,我试图从我的 HTML 表单中检索一些信息,但是,我没有得到任何信息,我已经尝试了所有方法,但似乎没有任何效果。

Routes.py

@app.route("/about", methods=['POST', 'GET'])
def about():
    name = request.form.get('name')
    lastname = request.form.get('lastname')
    msg = Message(
       subject='Hello ' + str(name),
       sender='kristofferlocktolboll@gmail.com',
       recipients=
           ['kristofferlocktolboll@gmail.com'],
       html= 'hello mr ' + str(lastname))
    mail.send(msg)
    confirm_msg = "Your message has been sent!"
    return render_template("about.html", confirm_msg=confirm_msg)

关于.html:

 <h1 class="mb-5"> Enter your message, and i will get back to you as soon as possible</h1>

          <form action="{{ url_for('about') }}" method="POST">
                First name: <br>
                <input type="text" name="name" size="35"><br>
                  Last name:<br>
                 <input type="text" name="lastname" size="35"><br>
                    Email-address: <br>
                 <input type="email" name="email" size="35"><br>
                 Phone-number: <br>
                 <input type="text" name="phone" size="35"><br>
                Enter your message: <br>
                 <textarea type="text" name="message" rows="7" cols="40"></textarea><br>
            </form>
            <br>
            <form>
              <button type="submit" class="btn btn-outline btn-xl js-scroll-trigger" value="submit" method="POST">Let's get in touch</a>
            </form>
            </div>
        </div>        
              </div>
            </div>
          </div>
        </div>
      </div>

我希望它是一个发布请求,但是每当我从 @app.route 中的方法中删除“GET”属性时,我都会收到“不允许使用方法”错误,这可能是因为它正在使用 GET 进行重定向。

电子邮件已成功发送,因此邮件 API 工作正常。但它是与值“无”一起发送的,其中 name 和 last name 属性在哪里。

编辑: 我必须将 name 和 last name 对象转换为字符串,否则会出现 Nontype 错误

【问题讨论】:

  • 创建两个单独的方法来获取输入并将其发送回,您的 about.html 接受输入,因此在获取值后以不同的方法呈现它。
  • 所以我不应该在邮件发送后渲染模板?
  • 我该怎么做?
  • 如何创建两个单独的方法?

标签: html post flask


【解决方案1】:

创建template/my-form.html

<form method="POST">
    <input name="name">
    <input name="lastname">
    <input type="submit">
</form>

在您的烧瓶应用程序routes.py

from flask import Flask, request, render_template

app = Flask(__name__)

@app.route('/')
def my_form():
    return render_template('my-form.html')

@app.route('/', methods=['POST'])
def my_form_post():
    name = request.form['name']
    lastname = request.form['lastname'] 
    <do your manipulation>
    return render_template(yourtemplate,processedtext = processedtext,somethingelse=somethingelse)

您可以将第二个渲染模板中的变量 grep 为

<html>
<body>
  {{processedtext}}
  {{somethingelse}}
</body>
</html>

并显示它们

【讨论】:

    猜你喜欢
    • 2011-05-14
    • 2017-09-24
    • 2017-10-15
    • 1970-01-01
    • 2019-11-30
    • 2012-01-20
    • 1970-01-01
    • 2017-05-28
    • 2020-08-24
    相关资源
    最近更新 更多