Skip to content Skip to sidebar Skip to footer

Python Flask: Pass Jinja Variable To Backend

I have a simple Flask web app showing a table that I read from a TSV file (using Pandas). For each row, I'm showing the index, some text, a label (positive/negative) a date, and a

Solution 1:

Why don't you utilize hidden form inputs? In your form, add the hidden input element:

{% for index, text, label, date in data %}
<tr><th>{{ index }}</th><th>{{ text }}</th><th>{{ label }}</th><th>{{ date }}</th><th><formaction="/edit"method="post"role="form"><inputtype="hidden"id="index"name="index"value="{{ index }}"><inputtype="submit"name="submit"value="Change Label"class="btn btn-info"></form></th></tr>
{% endfor %}

Then in your route:

@app.route('/edit', methods=['GET', 'POST'])defedit():
    if request.method == 'GET':
        return render_template('admin.html')

    if request.method == 'POST':
        index = int(request.form['index'])
        # Now use `index` to change your TSVreturn render_template('admin.html')

Solution 2:

For this kind of task I would suggest you to use url_for.

I would consider it the preferred way because it will allow you to build meaningful and always working URLs, without necessarily relying to a user form.

This will be of great help if you decide to make an API, for example or if your users decide to share bookmarks in order to quickly achieve specific functions in your webapp.

Here's a relevant example from the documentation (check URL Building if you want to read more):

from flask import Flask, url_for

app = Flask(__name__)

@app.route('/')defindex():
    return'index'@app.route('/login')deflogin():
    return'login'@app.route('/user/<username>')defprofile(username):
    return'{}\'s profile'.format(username)

with app.test_request_context():
    print(url_for('index'))
    print(url_for('login'))
    print(url_for('login', next='/'))
    print(url_for('profile', username='John Doe'))

Here's also an example of how to write the template from a small app I wrote (it has basic CRUD functionality so you might find it useful):

<divdata-role="content"><h3class="center">Edit restaurant</h3><labelfor="textinput-hide"class="ui-hidden-accessible">Text Input:</label><formid="new-restaurant-form"action="{{url_for('edit_restaurant', restaurant_id=restaurant.id)}}"method="POST"target="_parent"><inputtype="text"name="restaurant-name"id="textinput-hide"placeholder="{{restaurant.name}}"value=""><fieldsetclass="ui-grid-a"><divclass="ui-block-a"><ahref="#"data-role="button"data-data-theme="c">Cancel</a></div><divclass="ui-block-b"><buttontype="submit"data-role="button"data-transition="flow"data-theme="b"id="btn-add-new-ok">Ok</button></div></fieldset></form></div>

Post a Comment for "Python Flask: Pass Jinja Variable To Backend"