【问题标题】:Flask-WTForms error when specifying validator of maximum length指定最大长度的验证器时出现 Flask-WTForms 错误
【发布时间】:2019-11-01 08:45:08
【问题描述】:

我在让搜索栏的最大长度验证器与我的烧瓶应用程序一起使用时遇到了一些麻烦。我目前遇到错误:TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.

这是我的forms.py:

    class SearchForm(FlaskForm):
    query = StringField('query', validators=[DataRequired(), Length(max=20)])
    submit = SubmitField('????')

还有我在 routes.py 中的路线:

@app.route('/gsearch', methods=['POST'])
def gsearch():
    conn = sqlite3.connect("retro_games.db")
    cur = conn.cursor()
    form = SearchForm()
    if form.validate_on_submit():
        cur.execute("SELECT * FROM Games WHERE name LIKE ?",
                    ("%"+form.query.data+"%",))
        game = cur.fetchall()
        return render_template('gsearch.html', title='Search', game=game)

感谢您的帮助:)

【问题讨论】:

  • 如果if form.validate_on_submit(): 被证明是假的会发生什么?除了None,你没有返回任何东西

标签: python flask flask-wtforms wtforms


【解决方案1】:

当表单无效时你应该处理,

def gsearch():
    conn = sqlite3.connect("retro_games.db")
    cur = conn.cursor()
    form = SearchForm()
    if form.validate_on_submit():
        cur.execute("SELECT * FROM Games WHERE name LIKE ?",
                    ("%"+form.query.data+"%",))
        game = cur.fetchall()
        return render_template('gsearch.html', title='Search', game=game)
    # if form is not vaild, handle the logic here
    return {"error": "game not found"}

更多信息请查看FLASK-WTF Validating Forms

【讨论】:

    猜你喜欢
    • 2014-01-21
    • 2023-02-02
    • 2021-08-09
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-08
    • 2014-02-05
    相关资源
    最近更新 更多