I am trying to have a button in HTML that removes a row in the database when I click it. This is for a flask app. here is the HTML:
<div class="container-fluid text-center" id="products">
{% for product in productList %}
<div class='userProduct'>
<a href="{{ product.productURL }}" target="_blank">{{ product.title|truncate(30) }}</a>
<h4 class="currentPrice">${{ product.currentPrice }}</h4>
<h5 class="budget">Budget: {{ product.userBudget }}</h5>
<form action="{{ url_for('delete', id=product.id) }}">
<button class="btn btn-sm btn-primary" type="submit">Remove from Wishlist</button>
</form>
</div>
{% endfor %}
</div>
And here is the route in the python file
@app.route('/delete/<id>')
@login_required
def delete(id):
remove_product = Product.query.filter_by(id=int(id)).first()
db.session.delete(remove_product)
db.session.commit()
return redirect(url_for('dashboard'))
Is there anything wrong I am doing with url_for? I want to pass the id from the button to the python file so I can determine which entry to delete from the database.
You're probably passing ID as an integer and your route is expecting a string. Use this instead:
@app.route('/delete/<int:id>')
I just encountered the same error, In my case it was caused by some values being None in the database. So maybe check whether product.id has missing values.
To handle this, I needed an extra line, which would look something like this for you:
@app.route('/delete/<id>') # current line
@app.route('/delete', defaults={'id': None}) # added line which handles None
In delete(id) you then have to handle the case where id is None:
if id is None:
... # what should happen if id is None
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.