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 %}
...