Delete Records

Delete Route

Create a route to handle the deletion of the data. We do not need a template for this, as we can put the delete button wherever we like. Ensure to include an identifying variable (here we use cateogry_id) in order to query the correct record for deletion. Then do the delete -> save -> redirect pathway.

@app.route ("/delete_category/<int:category_id>")
def delete_category(category_id):
    category = Category.query.get_or_404(category_id)
    db.session.delete(category)
    db.session.commit()
    return redirect(url_for("categories"))

Defensive Programming

As deletion is irreversible, it is best practice to implement some sort of defensive programming to prevent accidental deletion of data.

One way of doing this is to make the delete button, not delete the record but to open a modal instead with a confirmation message, with the yes button linked to the delete function in the routes.

Another way would to be only show the delete button in the HTML file if the user is the one who created the item. In this scenario, there is a Model for User, which will have the login credentials and allow users to log in with a form. Then when they create items, there would be an attribute of user_id in the created item to reference back to the user. This can then be checked like so:

  • Have the user_id passed to the page through the route by checking the session: user_id = session.get("user_id")
  • Putting the delete button inside an if statement to only show if it was created by the logged in user: {% if user_id == toy.user_id %}{% endif %}