提交Flask

时间:2018-01-04 20:21:39

标签: python flask wtforms

出于某种原因,form.validate_on_submit()不返回任何内容。

from flask import Flask
from flask_wtf import FlaskForm
from wtforms import StringField, DecimalField, validators
from flask import render_template

app = Flask(__name__)
app.config.update(dict(
    SECRET_KEY="super awesome key"
))

class MyForm(FlaskForm):
    name = StringField('Product name', [validators.InputRequired(), validators.Length(min=0, max=30)])

@app.route('/', methods=['GET', 'POST'])
def index():
    form = MyForm()
    if form.validate_on_submit():
        return "Mission accomplished!"
    return render_template('submit.html', form=form)
{% macro render_field(field) %}
  <dt>{{ field.label }}
  <dd>{{ field(**kwargs)|safe }}
  {% if field.errors %}
    <ul class=errors>
    {% for error in field.errors %}
      <li>{{ error }}</li>
    {% endfor %}
    </ul>
  {% endif %}
  </dd>
{% endmacro %}

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>Add new grocery product</h1>
<p>Provide appropriate product details</p>
<form method="POST" action="/">
   {{ form.csrf_token }}
   {{ render_field(form.name.label) }} {{ form.name(size=20) }}<br>
   <input type="submit" value="Go">
</form>
</body>
</html>

应用程序本身应该以特定形式收集用户输入,并通过SQLAlchemy将其插入到数据库中。输出应该是:

  1. 返回&#34;完成任务!&#34;如果验证成功
  2. 返回验证哪个字段失败并显示错误消息&#34;此字段是必需的&#34;在submit.html模板上
  3. 修改

    Duo在代码方面取得了一些成功,我对问题进行了另一次编辑。如果验证失败,宏似乎不会显示适当字段的错误消息。

    即。如果字段名称为空,则宏应自行创建并显示错误消息(此字段不能为空)。

    最终编辑

    我设法找到了解决方案。如果render_field如下所示,Submit.html模板似乎会导致宏出现问题:

    {{ render_field(form.name.label) }}
    

    instaed of this:

    {{ render_field(form.name) }}
    

1 个答案:

答案 0 :(得分:0)

#This might help    
from flask import Flask
    from flask_wtf import FlaskForm
    #from wtform import SubmitField
    from wtforms import StringField, DecimalField, validators,SubmitField
    from flask import render_template

    app = Flask(__name__)
    app.config.update(dict(
        SECRET_KEY="super awesome key"
    ))

    class MyForm(FlaskForm):

您需要像这样

对您的验证器进行编辑
        name = StringField('Product name', validators = [InputRequired(), , Length(min=0, max=30)])
    #create submit option in your flask form
    submit = SubmitField("Submit")


    @app.route('/', methods=['GET', 'POST'])
    def index():
        form = MyForm()
        if form.validate_on_submit():
            return "Mission accomplished!"
        return render_template('submit.html', form=form)