Sorted Todos Template¶
We’re returning a list of todos, but they aren’t sorted. Let’s add that, and also show debugging in Python code, instead of just template code.
Steps¶
Your
app.py
should match the following:from flask import Flask from flask import render_template from models import populate_todos, Todo app = Flask(__name__) @app.route('/') def home_page(): return render_template('home_page.html', title='Home Page') @app.route('/todo/') def list_todos(): todos = Todo.list() return render_template('list_todos.html', title='List Todos', todos=todos) @app.route('/todo/<int:todo_id>') def show_todo(todo_id): todo = Todo.get_id(todo_id) return render_template('show_todo.html', title='Todo ' + str(todo_id), todo=todo) if __name__ == '__main__': populate_todos() app.run(debug=True)
Your
templates/list_todos.html
should match the following:{% extends "layout.html" %} {% block content %} <ul> {% for todo in todos %} <li> <a href="/todo/{{ todo.id }}">{{ todo.title }}</a> </li> {% endfor %} </ul> {% endblock %}
Your
templates/show_todo.html
should match the following:{% extends "layout.html" %} {% block content %} <p>{{ todo.title }}</p> {% endblock %}
Sorted Listings¶
- Back in models.py, we’re going to change
def list
to return a sorted listing - First, right-click Debug to run it under the debugger
- Then, refactor to extract the return value into a local variable
- Change to assign a sorted list to that variable
- Set a breakpoint on the assignment
- Ctrl-D and confirm
- Previous topic: List Todos Template
- Next topic: Navigation