0

I have a form which displays a list of values as buttons.

products = [ant,bat,cat,dog,egg]

Index.html

<form action="{{ url_for('show_products') }}" method="post">
      <ul class="list-group">
       {% for p in products %}
        <input type="submit" name="{{p}}" value="{{p}}" >{{p}}</input> 
        {% endfor %}
      </ul> 
      <button type="submit" class="btn btn-primary">Want to use this button to redirect</button>
    </form>

In app.py

@app.route('/show_products', methods=["POST", "GET"])
def show_products():
    result = []
    prod_data = {}
    if request.form:
            result = request.form
    prod_data['p_name'] = result
    return render('run_import.html', prod_data)

show_products.html

<h1>Hi</h1>
<p>p_name</p>

So everytime one of the products are clicked, ant, cat etc. The page immediately redirect to show_products.html and the name of the clicked product is shown.

I want the redirect to happen only when the button outside the for loop is clicked and every product that was clicked until then to be passed back as a list to show_products() and then to the html page.

2
  • 1
    can you share the route which is responsible for rendering the index.html templpate. Commented Sep 20, 2021 at 7:25
  • You could use checkbox to select multiple entries in a form and then one submit button. Would that help? Commented Sep 20, 2021 at 9:34

1 Answer 1

1

You can use a checkbox to capture multiple entries and send them back to flask on click of submit

flask.py

@app.get('/')
def index():
    products = ['ant','bat','cat','dog','egg']
    return render_template('test.html', products=products)

@app.post('/show_products')
def show_products():
    products = request.form.getlist('products')
    return render_template('output.html', products=products)

You can use CSS to make the checkboxes as per your requirement

test.html

<form action="{{ url_for('show_products') }}" method="post">
    <ul class="list-group">
        {% for p in products %}
        <input type="checkbox" name="products" value="{{p}}">{{p}}</input>
        {% endfor %}
    </ul>
    <button type="submit" class="btn btn-primary">Want to use this button to redirect</button>
</form>

output.html

<ul class="list-group">
    {% for p in products %}
        {{p}}
    {% endfor %}
</ul>

If you need to use buttons to capture the values, you will need an onClick listener on each button to store the values in a list and send the list over on click of submit

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

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.