π Introduction: Adding a New To-Do
In this lesson, we will create a page to add new tasks to our application.
This page will allow users to:
Enter a title and description for a task.
Set a priority level π―.
Submit the task β so it appears in their personal to-do list β .
By the end of this lesson, users can add tasks directly from the web interface.
β Step 1: Create the Add To-Do Template
In the templates folder, create a new file:
add-todo.htmlDelete any auto-generated content.
Include the main layout for consistency:
{% include 'layout.html' %}ποΈ Step 2: Build the Add To-Do Form
Add the following structure inside add-todo.html:
<div class="container">
<div class="card">
<div class="card-header">π Make a New To-Do</div>
<div class="card-body">
<form id="todo-form">
<!-- Title Field -->
<div class="form-group">
<label>Title</label>
<input type="text" class="form-control" name="title" required>
</div>
<!-- Description Field -->
<div class="form-group">
<label>Description</label>
<textarea class="form-control" rows="3" name="description" required></textarea>
</div>
<!-- Priority Field -->
<div class="form-group">
<label>Priority π―</label>
<select class="form-control" name="priority">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
<!-- Action Buttons -->
<button type="submit" class="btn btn-primary">β Add New To-Do</button>
<a href="/todos/todo-page" class="btn btn-success">π Back</a>
</form>
</div>
</div>
</div>Explanation:
id="todo-form"β Important for JavaScript interaction.titleanddescriptionβ Task details.priorityπ― β Indicates task importance.Backπ β Returns to the main To-Do list.Add New To-Doβ β Submits the form.
β‘ Step 3: Create the Endpoint in todos.py
Add a page endpoint for rendering the Add To-Do page:
@router.get("/add-todo-page")
async def render_add_todo_page(request: Request, db=Depends(get_db)):
try:
user = await get_current_user(request.cookies.get("access_token"))
if user is None:
return redirect_to_login()
return templates.TemplateResponse("add-todo.html", {"request": request, "user": user})
except:
return redirect_to_login()Explanation:
Fetches the current user using JWT.
Redirects to login if user is invalid.
Passes the
userobject for navbar and permissions.
β Step 4: Test the Add To-Do Page
Start your FastAPI application.
Navigate to
/auth/login-pageand log in:
Username: codingwithRuby
Password: test1234!Click Add New To-Do.
Fill out the form:
Title:
New To-DoDescription:
This is our new to-doPriority:
3
Click Add New To-Do β β task is submitted.
Click Back π β verify the new task appears in the To-Do list β .
π― Summary
Created a dedicated Add To-Do page π.
Users can enter title, description, and priority π―.
Integrated navigation with the main layout.
Endpoint ensures only authenticated users can access the page.
Form submission successfully updates the To-Do list β .