【问题标题】:switch/toogle results in BadRequestKeyError: 400 Bad Requestswitch/toogle 导致 BadRequestKeyError: 400 Bad Request
【发布时间】:2021-11-04 08:35:21
【问题描述】:

我有一个使用 python 和烧瓶生成的 index.html,它显示了一个列表。我想通过引导开关过滤这个列表。现在我有以下代码,它可以通过 GET 请求显示我的 index.html 列表。启用开关也可以工作并显示过滤列表。但是当切换回未过滤/关闭时,我收到了一个错误的请求。问题在于 switchvalue = request.form['switch'] 但我不明白为什么会这样。

Python 代码:

@app.route('/', methods=['POST', 'GET'])
def index():
    conn = get_db_connection()

    if request.method == 'POST':
        switchvalue = request.form['switch']
        flash(switchvalue)

        if switchvalue == '1':
            rows = conn.execute('SELECT Name, CAST (Points AS int) as Points, isActive FROM table WHERE isActive = "Active"').fetchall()
            conn.close()
            return render_template('index.html', rows=rows, switchcheck=1)

    rows = conn.execute('SELECT Name, CAST (Points AS int) as Points, isActive FROM table').fetchall()
    conn.close()
    return render_template('index.html', rows=rows, switchcheck=0)

HTML:

...
{% block content %}
    <h1>{% block title %} Title {% endblock %}</h1>
    <form method="POST" action="{{ url_for('index') }}">
         <div class="custom-control custom-switch">
             {% if switchcheck == 0 %}
                 <input type="checkbox" name="switch" onclick=this.form.submit() value="1" class="custom-control-input" id="customSwitch1">
             {% else %}
                 <input type="checkbox" name="switch" onclick=this.form.submit() value="0" class="custom-control-input" id="customSwitch1" checked>
             {% endif %}
             <label class="custom-control-label" for="customSwitch1">Active</label>
         </div>
    </form>
    {% for row in rows %} 
...

【问题讨论】:

    标签: python sqlite flask bootstrap-4


    【解决方案1】:

    因此,开关的值似乎没有被发布,因为开关被作为复选框处理,并且当它们未被选中时,它们不会提交值。因此 submit.form(switch) 看不到数据。

    我在这里找到了我的提示:How to utilize Bootstrap Ti Ta Toggle Checkbox with Flask

    还提到使用带有 name=switch 的隐藏表单来处理这个问题,但对我来说没有成功。我的解决方法如下:

    try:
        switchvalue = request.form['vrswitch']
    except:
        switchvalue = 0
    

    我敢打赌,有更优雅的方法可以做到这一点,但它确实有效!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-25
      • 2018-09-21
      • 1970-01-01
      • 2016-05-06
      • 1970-01-01
      • 2012-10-27
      • 2017-03-08
      相关资源
      最近更新 更多