Creating ToDos with User Input
Creating ToDos with User Input
Welcome to the next lesson in our journey of building a ToDo App with Flask! In this lesson, we will focus on allowing users to create new Todo items through user input. This feature is essential because it empowers users to interact with the app and manage their tasks efficiently. By the end of this lesson, you will be able to accept input from users, create new Todo items, and display them within the application.
Defining the Add Method in TodoService
Let's first update our TodoService to create new Todo items from user input by adding a method that takes a title and description, generates a unique ID, and adds the new Todo to the list.
In this code, we define a method named add that receives a title and description, generates a new unique ID for the Todo item, creates the Todo object, and then adds it to the list of Todos:
- Generate a New ID: We calculate the new ID by adding 1 to the maximum existing ID, or by starting at 1 if the list is empty.
- Create a New Todo Object: We use the new ID, title, and description to create a new
Todoobject. - Add the Todo to the List: We append the new
Todoobject to the_todoslist.
This approach ensures that each new Todo item has a unique ID and captures user input effectively. Now that we have addressed the service layer functionality for adding a Todo, let's move on to creating the controller endpoint to handle incoming user requests.
Creating the Add Route
Next, we need to update our controller to handle user input and add new Todo items. In todo_controller.py, let's add a new route to handle POST requests for adding new Todo items:
In the /add route, we handle the form submission from the user. A form is an HTML element that allows users to input data and send it to the server. When the user submits the form, it sends the data using a POST request, which is used in HTTP to send data to the server for creating or updating resources. We retrieve the data from the form using request.form.get() to get the values of the title and description fields.
After retrieving the form data, we check that both the title and description are provided. If they are, we call the add method of TodoService to create a new Todo item with the provided information. This adds the new item to our list of Todos.
Finally, we use redirect(url_for('todo.list_todos')) to send the user back to the main Todo list page. The redirect function tells the browser to open a different page, which, in this case, is the Todo list page. This refreshes the page so the user can see the new item they just added.
