Adding and Subtracting Buttons on a Bottle Designed Web Page

I currently have a bottle app that reads items from a sqlite database and displays them in a table (using beer because ok ... I like beer). I want to be able to customize the number in the table (quantity) using the add and subtract buttons on the table row. The buttons should update the quantity in the database and update the quantity displayed on the page.

This is the python / bottle part:

@app.route('/')
@app.route('/display')
    def display():
    conn = sqlite3.connect('beers.db')
    c = conn.cursor()
    c.execute("SELECT id, brewer, beer, amount FROM beer;")
    result = c.fetchall()
    c.close()

    output = template('make_table', rows=result)
    return output

      

This is the current template with add and subtract buttons.

<p>The available beers are:</p>
<table border="1">
%for row in rows:
    <tr>
    %for col in row:
        <td>{{col}}</td>
    %end
        <td><input type ="button" value="Add"></td>
        <td><input type ="button" value="Subtract"></td>
    </tr>
%end
</table>

      

Thanks for any help!

+3


source to share


1 answer


Add a route /display

using the method POST

.

In this case, catch the value of the beer ID and if the user clicked the "Add" or "Sub" button.

Once this is done, you will get the beer id and the action you need to do, you just need to render your stuff using a DB and redirect to the page /display

.

Here's the bottle app code:



@app.route('/display', method='POST')
def display_mod():
    #You get the value of each button : None if non clicked / Add or Sub if clicked
    add = request.POST.get('Add')
    sub = request.POST.get('Sub')
    # b_id is the ID of the beer the user clicked on (either on add or sub)
    b_id = request.POST.get('beer_id')

    if add is not None:
        # do something
        redirect("/display")

    if sub is not None:
        # so something
        redirect("/display")

      

Then change your template to include the form and change the two buttons in the submit button. You also need to put the input hidden

so that you can pass data to the application.

<p>The available beers are:</p>
<table border="1">
%for row in rows:
    <tr>
    <!-- Here you grab the beer ID that you'll use later -->
    %p_id = row[0] 
    %for col in row:
        <td>{{col}}</td>
    %end
        <form action="/display" method="POST">
            <!-- input type hidden, and value is the ID of the beer -->
            <input type = "hidden" name ="beer_id" value= "{{p_id}}">
            <td><input type ="submit" name="Add" value="Add"></td>
            <td><input type ="submit" name="Sub" value="Subtract"></td>
        </form>
    </tr>
%end
</table>

      

And there you go. Hope this helps (if yes, feel free to send me a beer!)

+2


source







All Articles