News from this site

 Rental advertising space, please contact the webmaster if you need cooperation


+focus
focused

classification  

no classification

tag  

no tag

date  

no datas

Flask return redirect not working after delete

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!


solution


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



Category of website: technical article > Q&A

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.

4 0
collect article
collected

Comment content: (supports up to 255 characters)