0

I have an index.html generated with python & flask that shows a list. I want to filter this list by a bootstrap switch. Now I have the following code and it works to show my index.html list by GET request. enabling the switch also works and shows the filtered list. But when switching back to unfiltered/off I receive a bad request. the problem is with switchvalue = request.form['switch'] but I dont understand why this is.

Python code:

@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 %} 
...
fk1
  • 33
  • 5

1 Answers1

0

So it seems like the value of switch does not get POSTed because switches are handled as checkboxes and when they are not checked they dont submit value. therefore submit.form(switch) doesnt see data.

I found my hint here: How to utilize Bootstrap Ti Ta Toggle Checkbox with Flask

Also there is mentioned to use hidden form with name=switch to handle this problem but was no success for me. My workaround looks as follows:

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

I bet there are more elegant ways to do this but it works!

fk1
  • 33
  • 5