Jam3sn
Jam3sn

Reputation: 1087

How do I set up a Flask request to change the color of an HTML button?

I'm having difficulty understanding Flask requests. I'm using it to change the state of a HTML button once it's been clicked, essentially changing the color from black to yellow. But I'm struggling to find how to link the Python and the HTML.

Here's my Python so far:

from flask import Flask, render_template, url_for, request

app = Flask(__name__)

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

    pageType = 'Controller' 
    btn1 = True

    if request.form['value'] == 'on':
        print("yes")
        btn1 = True
    elif request.form['value'] == 'off':
        print("no")
        btn1 = False

    return render_template("index.html", pageType = pageType, btn1 = btn1)

if __name__ == "__main__":
    app.debug = True
    app.run()

And then in my HTML Template:

<form method=post>
    {%  if btn1 == True  %}
        <button type=submit class="btn btn-default" value="on"><i class="fa fa-lightbulb-o fa-5x" style="color:yellow;"></i><br>Lamp</button>
    {% else %}
        <button type=submit class="btn btn-default" value="off"><i class="fa fa-lightbulb-o fa-5x"></i><br>Lamp</button>
    {%  endif  %}
</form>

I clearly have gone wrong, just not sure where or how to make this work...

Upvotes: 0

Views: 6854

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599866

All HTML form elements need a name attribute in order for their data to be sent when the form is submitted. Your template should be:

{% if btn1 %}
    <button type=submit class="btn btn-default" name="lamp" value="on">...
{% else %}
    <button type=submit class="btn btn-default" name="lamp" value="off">...
{% endif %}

And that name is what you use to access the value from the request:

if request.method == 'POST':
    if request.form['lamp'] == 'on':
        btn1 = True
    elif request.form['value'] == 'off':
        btn1 = False

Upvotes: 4

Related Questions