【问题标题】:Checkbox checked flask复选框检查烧瓶
【发布时间】:2018-06-26 21:06:15
【问题描述】:

我对表单中的复选框有疑问

<form id="form" action="/findPkgInstalled" role="form" method = "POST">
    <div class="input-group col-xs-4">
      <input type="text" name="pkgSearch" placeholder="Ricerca applicazione non installate..">
      <div class="input-group-btn">
        <button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
      </div>
    </div>
    <h6><input type="checkbox" name="filterName" checked>Filtra per nome</h6>
</form>

在 Python 中我有:

@app.route('/findPkgInstalled', methods=['POST'])
def findPkgInstalled():
    error = None
    pkg = request.form['pkgSearch']
    if not pkg:
        flash(u'Operazione errata, impossibile ricercare stringa vuota','warning')
        return redirect(url_for('listInstalled'))
    else:
        if request.form['filterName'] is 'on':
            appFound = aptsearch(pkg,True)
            return render_template('find-pkg-not-installed.html', appFound = appFound)
        else:
            appFound = aptsearch(pkg,False)
            return render_template('find-pkg-not-installed.html', appFound = appFound)
    return redirect(url_for('listInstalled'))
    box = request.form['filterName']

但这不起作用。报告的错误是 400 Bad Request。我能怎么做?你能帮帮我吗?

【问题讨论】:

    标签: html python-3.x flask


    【解决方案1】:

    此错误表示您尝试使用不正确的键从您的发布请求中获取对象。例如,如果您取消选中 filterName 复选框 - 这将导致此错误:

    request.form['filterName']
    

    我的建议:

    0) 始终检查您的帖子正文,以了解您可以使用哪些键从该正文中检索值。

    1) 使用

    request.form.get('filterName')
    

    而不是

    request.form['filterName']
    

    因为.get()返回None是没有这样的键而不是在flask内抛出异常导致400错误

    2) 使用

    request.form.get('filterName') == 'on'
    

    而不是

    request.form['filterName'] is 'on'
    

    因为如果两个变量指向内存中的同一个对象,is 返回 True。我不确定你是否已经在进程内存中有“on”对象

    【讨论】:

    • 谢谢!我检查 request.form.get('filterName') 是否为 None ......它有效! :)
    猜你喜欢
    • 2014-01-23
    • 2015-11-18
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    • 2019-11-08
    • 1970-01-01
    • 1970-01-01
    • 2014-07-21
    相关资源
    最近更新 更多