no classification
no tag
no datas
posted on 2023-11-12 14:29 read(922) comment(0) like(4) collect(4)
Help, I'm new to FLask and Python. I'm not sure why, but the return redirect is not working. When I click the button, the item is getting deleted, but it doesn't redirect or flash the message. If I click home afterward the success message is then flashed.
@app.route('/stuff/<thing_id>', methods=['DELETE'])
def delete_thing(thing_id):
error = False
thing = thing.query.filter(thing.id == thing_id).one_or_none()
if thing is None:
return render_template('errors/404.html')
try:
db.session.delete(thing)
db.session.commit()
except:
error = True
flash('An error occurred. thing ' + thing.name + ' could not be deleted.')
db.session.rollback()
print(sys.exc_info())
finally:
db.session.close()
if not error:
flash('thing ' + thing.name + ' was successfully deleted!')
return redirect(url_for('index'))
In my template I have:
<button id="delete-thing" data-id="{{ thing.id }}" class="btn btn-default btn-sm">
Delete Thing
</button>
<script>
const deleteBtn = document.getElementById('delete-thing')
deleteBtn.onclick = function(e) {
let result = confirm("Are you sure? This will permanently delete this thing!");
if (result) {
const thingId = e.target.dataset['id']
fetch('/stuff/' + thingId, {
method: 'DELETE'
})
}
}
</script>
Thanks for your help!
This javascript fetch thing performs so called ajax call. It means that it will call the server and fetch the result and then it does what you tell it to do. And you didn't say anything, so it does not do anything with the returned value. So that's why nothing happens when you click the button.
But your server code sets the flash message, and it will be shown the next time when you actually load any page from the server.
How to fix that? Well, it pretty much depends on your expected workflow. I myself consider using ajax calls an advanced topic. Ajax calls are better suited for SPAs (single page applications). I would recommend you to go for a traditional way, using the good old html forms with a POST method. Once you get familiar with that, you will be able to advance. Anyway, this is more of a javascript question than python/flask/sqlalchemy, because that part is correct on your side.
Anyway, to let you see what's hapening, you could try something like this:
fetch('/stuff/' + thingId, {
method: 'DELETE'
}).then(function(response) {
if (!response.ok) {
console.log("Error", response);
} else {
console.log("Success", response);
// this is kind-of silly, but should help you achieve what you want
// location.reload()
}
})
And fire up your web browser's console to see the debug prints. See: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
Author:qs
link:http://www.pythonblackhole.com/blog/article/245159/71ce32d7fb76ad15058a/
source:python black hole net
Please indicate the source for any form of reprinting. If any infringement is discovered, it will be held legally responsible.
name:
Comment content: (supports up to 255 characters)
Copyright © 2018-2021 python black hole network All Rights Reserved All rights reserved, and all rights reserved.京ICP备18063182号-7
For complaints and reports, and advertising cooperation, please contact vgs_info@163.com or QQ3083709327
Disclaimer: All articles on the website are uploaded by users and are only for readers' learning and communication use, and commercial use is prohibited. If the article involves pornography, reactionary, infringement and other illegal information, please report it to us and we will delete it immediately after verification!