1

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.routes()

@app.route('/add', methods=['POST'])
def add():
    star_faves = current_user.favorites
    star_faves_list = star_faves.split(', ')
    star_faves_list.append('Cherries')
    ', '.join(star_faves_list)
    current_user.favorites = star_faves_list
    db.session.commit()
    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.

aalberti333
  • 1,181
  • 1
  • 14
  • 24

1 Answers1

1

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">
</form>

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');
request.send();
martonbognar
  • 462
  • 3
  • 14
  • Thanks @martonbognar , I think I understand the logic a bit better now, and the communication between my python and the HTML snippet is now up and running. As for the database update, I realize I wasn't saving the `', '.join()` statement to a variable. Assigning that ended up doing the trick. – aalberti333 Mar 14 '18 at 13:02