In this final lesson, we will cover how to enable the delete button so that you can delete a booking from your system. If you have followed along with the previous video, you should now have a functional form for updating individual records in your database. We will now implement the delete functionality, allowing users to remove bookings from the system.
First, navigate to the code where we have set up our last endpoint, named
delete. In the delete endpoint, we will start by fetching the database and getting a cursor object. The cursor object is necessary for querying the database.
# Get the database and create a cursor
db = get_db()
cursor = db.cursor(dictionary=True)
Before deleting a booking, we need to ensure that the booking exists in the database. To do this, we will use a
SELECT statement with a small trick. Instead of selecting the booking record, we will select the number
1 if the booking exists in the database.
# Check if the booking exists
cursor.execute("SELECT 1 FROM booking WHERE reference_number = %s", (reference_number,))
booking = cursor.fetchone()
If the result of the query is
None, it means that the booking does not exist in the database. We can abort the delete process in this case:
# Abort if booking is not found
if booking is None:
Once we have confirmed that the booking exists in the database, we can proceed to delete it. To do this, we will use a
# Delete the booking
cursor.execute("DELETE FROM booking WHERE reference_number = %s", (reference_number,))
We also need to commit the changes to the database and close the cursor:
Now, let's test the delete functionality. Navigate to the booking list and select a booking. Click the delete button and observe that the booking has been removed from the list.
In this final lesson, we have demonstrated how to enable the delete button in a Flask web app, allowing users to remove bookings from the system. The essential steps include setting up the delete endpoint, verifying if the booking exists in the database, and then performing the actual deletion.
The code should now be able to:
- View the list of all the records in the database.
- Get information from different tables, e.g., guest name and room type.
- Create new reservations in the system.
- Update reservations.
- Delete reservations.
With these capabilities, your web app should now be fully functional for managing bookings!
About this lesson
In this lesson, you'll learn how to wire up your delete endpoint to delete a booking from your Flask application.
I’m a software developer and educator focused on helping others build their dream software projects.
Feedback or questions? Reach out to our team at firstname.lastname@example.org.