Home > Net >  How can I ask the user again before deleting a record from the database
How can I ask the user again before deleting a record from the database

Time:10-21

My index.html file shows all posts in a blog. The index.html file contains a part that allows the user to delete a certain post. Here is the html code

<p >Posted by
            <a href="#"> {{ post.author.name }} </a>
            on {{post.date}}
            {% if current_user.id == post.author.id %}
            <a href="{{url_for('delete_post', post_id=post.id) }}">✘</a>
            {% endif %}
          
          </p>

If '✘' is pressed following function in main will be called:

@app.route("/delete/<int:post_id>")
@admin_only
def delete_post(post_id):
    post_to_delete = BlogPost.query.get(post_id)
    db.session.delete(post_to_delete)
    db.session.commit()
    return redirect(url_for('get_all_posts'))

I would like to insert a message which asks the user if he really wants to delete the post and only when the user clicks 'yes' the post will be really deleted in the database. Can anybody help me?

CodePudding user response:

There are many options. find here one of them

In your html, when the user clicks on delete, point to this route

@app.route("/deletewarning/<int:post_id>")
@admin_only
def deleteWarning_post(post_id):
    post_to_delete = BlogPost.query.get(post_id)
    return render_template('deletewarning.html', post_to_delete=post_to_delete)

In the deletewarning.html, give the user two links. One that points to 'delete_post' and one that points to 'deleteCanceled'

@app.route("/deletecanceled/<int:post_id>")
@admin_only
def deleteCanceled_post(post_id):
    post_to_delete = BlogPost.query.get(post_id)
    flash(f"delete of {post_to_delete.subject} was canceled")
    return redirect(url_for('get_all_posts'))

Now the user has the option to cancel the delete.

  • Related