4

I have this in index.html:

            {% for item in data %}
            <tr>
            <td>{{item[0]}}</td>
            <td>{{item[1]}}</td>
            <td>{{item[2]}}</td>
            <td>{{item[3]}}</td>
            <td>{{item[4]}}</td>
            <td>{{item[5]}}</td>
            <td>{{item[6]}}</td>
            <td>{{item[7]}}</td>
            <td>{{item[8]}}</td>
            <td>{{item[9]}}</td>
            <td>{{item[10]}}</td>
            <td>
                    <form action="{{ url_for('history') }}" method="POST">
                    <button type="submit"> History </button>
                    </form>
            </td>
            </tr>
            {% endfor %}

And this in app.py:

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

    return render_template('history.html')

So my webpage has a table with a bunch of rows and each row as a button labeled 'History'. Since right now each button does the same thing and points to history(), how can i distinguish which row of data the original click came from?

1
  • Why not just create select field in form ? With tables, you repeat almost same code multiple times. Form is for passing data to server, tables are just for representing something in tabular order... Commented Dec 6, 2018 at 17:48

2 Answers 2

2

You'll have to add the item ID into the HTML form, but you can not display it. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/hidden

Something like the following

<form action="{{ url_for('history') }}" method="POST">
    <input id="historicalId" name="historicalId" type="hidden" value="{{item.id}}">
    <button type="submit"> History </button>
</form>

Then in flask, you'll need to parse out the request form body

Sign up to request clarification or add additional context in comments.

Comments

2

I am writing this answer as it may help someone hopefully. Check the every table row is displaying a book and there is an edit button at the end of the table row.

           {% for book in books %}
            <tr>
                <td>{{ book[1] }}</td>
                <td>{{ book[2] }} </td>
                <td>{{ book[3] }} </td>
                <td>{{ book[4] }} </td>
                <input id="book_id" name="book_id"
                       type="hidden" value="{{ book[0] }}">
                <td><button type="submit" name="edit" value="{{ book[0] }}"
                            formmethod="post">Edit</button></td>
            </tr>

Every row has a hidden book_id which is used to retrieve the book in the backend using the below code:

        if request.form.get("edit"):
        print('Book ID: ', request.form.get('edit'))

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.