Button click in HTML to update SQLAlchemy db in Flask

I'm trying to update a database value called ''favorites'' for the logged in user of a Flask web app using a button click. Essentially, the favorites column is a single string that looks like this: Apples, Bananas, Oranges where on the button click, I would want to append a value (say Cherries) by breaking apart the string into a list in my @app.routes(), appending the value, and rejoining it back into a string before committing the changes. I'm not sure what the proper way is to do this, here's what I have:

HTML snippet

<button action="{{ url_for('add') }}" method="post" type="submit">Favorite</button>


@app.route('/add', methods=['POST'])
def add():
    star_faves = current_user.favorites
    star_faves_list = star_faves.split(', ')
    ', '.join(star_faves_list)
    current_user.favorites = star_faves_list
    return render_template('add.html')

The problem is that I don't really understand how the HTML is communicating with Python/Jinja, if anybody can help clear that up I would greatly appreciate it.

1 answer

  • answered 2018-03-13 22:24 martonbognar

    It looks like you have some elements confused.

    If you want to submit a POST request to the /add page, the easiest way is to create a form. (Buttons do not have an action or method attribute, forms do.) When you create the form, you also specify the HTTP method to use when submitting the form. So in your case, it should look something like this:

    <form action="{{ url_for('add') }}" method="POST">
         <input type="submit" value="Favorite">

    You can use a button instead of an input with type submit, they are interchangeable.

    If you don't want the page to reload while submitting the request, a more advanced technique you can use with JavaScript is something called AJAX.

    This example code sends the same POST request to the /add page:

    var request = new XMLHttpRequest();
    request.onreadystatechange = function () {
        // this method gets called if the state of the request changes (it succeeds of fails)
        // you will probably want to update your page accordingly here
    request.open('POST', '/add');