0

When I press either of these <input>'s, the Led does not get updated on the page.

.py:

from flask import Flask, request, render_template

app = Flask(__name__)
default_val = True


@app.route('/switch_led', methods=['GET', 'POST'])
def led_handler():
    on = request.form.get('ON', default_val)
    off = request.form.get('OFF', default_val)
    if on:
        Led = 'ON'
    elif off:
        Led = 'Not ON'
    return render_template('index.html', Led=Led)

index.html:

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
</head>
<body>
    <h1>{{ Led }}</h1>
    <form action="/switch_led" method="POST">
        <p><input type="submit" name="btnled" value="ON"></p>
        <p><input type="submit" name="btnled" value="OFF"></p>
    </form>
</body>
</html>

Any help is appreciated, thank you!!

5824
  • 3
  • 3

1 Answers1

0

Look closely:

default_val = True # this is important!
...

on = request.form.get('ON', default_val)
off = request.form.get('OFF', default_val)
if on:
    Led = 'ON'

So, when you click the OFF button, form.get('ON', default_val) will fail to find the ON toggle and return the default instead... which equals True!

The first condition you check is if on:, but, according to the logic above on is always True, so your LED will always stay ON. The elif condition doesn’t matter because the first one is always satisfied.

ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • When I remove `default_val`, I get an UnboundLocalError saying: local variable 'Led' referenced before assignment. So the whole HTML page won't load. – 5824 Mar 14 '19 at 21:03
  • @5824, there’s also a flaw in your HTML, which can be fixed [like this](https://stackoverflow.com/questions/22579616/send-value-of-submit-button-when-form-gets-posted). – ForceBru Mar 14 '19 at 21:22
  • could you explain, I do have the `name`s the same for both buttons – 5824 Mar 14 '19 at 22:23
  • @5824, you do, but you’re trying to get the values of the _names_ ON and OFF, which don’t exist. You should pass the individual (unique!) names of your buttons to `request.form.get`. – ForceBru Mar 15 '19 at 06:44