Updating Existing ToDos
Updating Existing ToDos
Welcome back! You've already made great progress by learning how to list and create todo items in your Flask application. Now, we will enhance your ToDo app by adding the ability to edit existing todo items. This feature is essential in any task management app, as it allows users to update and refine their tasks as needed.
By the end of this lesson, you will be able to:
- Retrieve an existing todo item for editing.
- Update the todo item with new details and save the changes.
Let's dive in!
Service Layer: Updating Todos
First, let's focus on the TodoService class and the update method. This method will allow us to modify the existing todo items.
Here, we define two methods within the TodoService class. The get_by_id method searches for and returns a todo item by its unique identifier. If found, the item is returned; otherwise, None is returned.
The update method leverages this retrieval functionality and updates an existing todo item's title and description. If the item is found and updated, the method returns True; otherwise, it returns False.
Controller Layer: Handling Edit and Update Requests
Now, let's move on to the controller layer. We will handle routes for displaying the edit form and for submitting updates.
Here are the relevant routes in todo_controller.py:
In this segment, we set up two new routes:
- Edit Route: The
edit_todoroute displays a form for editing a specific todo item. It uses theget_by_idmethod to retrieve the item and renders thetodo_edit.htmltemplate for editing. If the item isn't found, it redirects back to the list view. - Update Route: The
updateroute handles form submission, extracts the new title and description from the request, updates the todo item using theupdatemethod, and then redirects back to the main todo list. Although there are other HTTP methods more suited for update operations, such as PUT, we will use POST because HTML forms only natively support GET and POST methods.
Note that we use route parameters (e.g., <int:todo_id>) to capture dynamic values directly from the URL. For example, <int:todo_id> means todo_id is an integer parameter. In a URL, it might look like /edit/1 where 1 is the todo_id.
This allows us to pass the specific todo_id to the route functions for precise item handling.
