Keys the Script Reads
Part of the JSON APIs section of Coddy's Django journey. Lesson 13 of 19.
The new app.js adds a summary above the list, built from /api/stats/. The script and your Django code have to agree on names: the ids the script looks up on the page, and the keys it reads from the JSON.
const stats = await response.json();
summary.textContent = stats.open + " open, " + stats.done + " done";stats.done reads the key "done" from your JSON. A key the JSON lacks raises no error: JavaScript reads it as undefined and prints that word on the page. A missing id fails as quietly, with an error only in the browser's console. So read the script first: its names decide yours, letter for letter.
Challenge
MediumRead the new app.js, then give it what it needs.
- In
tasks/templates/tasks/home.html, add the summary paragraph with the id the script looks up, above the script tag. - In the
statsview intasks/views.py, add the key the summary reads (find it afterstats.inapp.js). Its value is the number of tasks not done.
Press Run: the summary reads 2 open, 1 done.
Try it yourself
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Task tracker</title>
</head>
<body>
<h1>Task tracker</h1>
<ul id="task-list"></ul>
<script src="{% static 'tasks/app.js' %}"></script>
</body>
</html>
All lessons in JSON APIs
Practice on your own: Django playground