Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask return redirect not working after delete

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!

like image 522
Tom McGinty Avatar asked Mar 28 '26 06:03

Tom McGinty


1 Answers

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

like image 51
Petr Blahos Avatar answered Mar 29 '26 20:03

Petr Blahos