I want a switch in my flask webapp to enable/disable the autopilot function of an IoT device. The switch only seems to work when moving from the OFF to ON position.
If you try to switch it from ON to OFF, it just reloads the page and leaves the switch in the ON position.
In the HTML template I loop through all the devices to display their Autopilot status with a switch. On click the form gets posted. Here is a simplified piece of the code.
{% for device in devices %}
<form method="POST">
<div class="form-check form-switch">
<label class="form-check-label" for="{{device.unique_id}}.autopilot">Autopilot</label>
<input class="form-check-input" type="checkbox" name="{{device.unique_id}}.autopilot" {% if device.autopilot %}checked{% endif %} onclick="submit();">
{% endfor %}
Here is an example of what the switch looks like
In the flask app.py I have a list of devices and when a POST request is sent, it loops through the devices list to check which autopilot to turn on or off.
@app.route('/', methods=['GET', 'POST'])
def home():
global devices
if request.method == "POST":
# decode response & filter out the unique ID
response = request.get_data().decode("utf-8")
resp_device_id = response.split(".")[0]
# compare unique ID with devices & toggle autopilot
for d in devices:
if str(d.unique_id) == resp_device_id:
d.autopilot = not d.autopilot
else:
print(str(d.unique_id) + "&" + resp_device_id + "do not match")
return render_template('home.html', devices = devices)
Everything works when switching from OFF to ON. But the POST response seems empty when switching from ON to OFF. And so the IF statement results in FALSE and nothing gets switched.
Any ideas what could go wrong here?
I figured it out eventually. Appearantly this is the expected behavior.
The page doesn't send the data if the box is unchecked. So the response is actually empty. To identify the switch, I added a hidden field to the form. Like this:
<input type="hidden" id="{{device.unique_id}}" name="device" value="{{device.unique_id}}">