4

I'm wondering why this isn't working as planned. The table below is in a form. Every table row has a book id and book title. The book title is formatted as a button, so that I can use the post method on form submission. When the button is clicked, the method (as shown below) fires well enough, but the book id isn't passed along to the method. I need the book id passed to the underlying method, as it will be used in a SQL query. Is there a way for me to make this happen?

{% block body %}
<div class="align-center">
    <form action="{{ url_for('books') }}" method="post">
        <table class="table">
            <thead>
                <tr>
                    <th></th>
                    <th>Book ID</th>
                    <th>ISBN #</th>
                    <th>Title</th>
                    <th>Author</th>
                </tr>
            </thead>
            <tfoot>
                <tr>
                    <td colspan="6"></td>
                </tr>
            </tfoot>
            {% for book in books %}
            <tr>
                <td></td>
                <td name="bookid">{{ book.id }}</td>
                <td name="bookisbn">{{ book.isbn }}</td>
                <td name="booktitle"><button btn style="border:none; border-bottom: 1px solid black;">{{ book.title }}</button></td>
                <td name="bookauthor">{{ book.author }}</td>
            </tr>
            {% endfor %}
        </table>
    </form>
</div>
{% endblock %}

And here's the Flask method to which I'm posting:

@app.route("/books", methods=["POST"])
@login_required
def books():
    bookid = request.form.get("bookid")
    return render_template("books.html", message=bookid)

2 Answers 2

6

You can submit values from the HTML form only using <input> elements. So, you need to either convert your <td name="..."> elements to <input>s or add a hidden input near each <td>:

...
<td name="bookid">{{ book.id }}</td>
<input type="hidden" name="bookid" value="{{ book.id }}" />
<td name="bookisbn">{{ book.isbn }}</td>
<input type="hidden" name="bookisbn" value="{{ book.isbn }}" />
...
Sign up to request clarification or add additional context in comments.

1 Comment

I had no idea that submission was off of the input field. Everything seemed to key off of the "name" attribute, which is a stupid inference in retrospect. Thanks for the help and the education!
1

Why not try adding it this way?

<td name="booktitle"><button btn value={{book.id}} style="border:none; border-bottom: 1px solid black;">{{ book.title }}</button></td>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.