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!