StaffCoder
Django
DjangoDjango 5.2Python 3.13
18 modules · 72 challengesSign up
Module 15 · Caching

Fragment Cached Sidebar

mediumDjango CachingCaching—No data yet

Problem statement

In this Django project, let the newsroom's trending sidebar be a leftover from an earlier request while the rest of the category page stays live. The job behind the sidebar scores every published story in the section one by one, it runs on every request for every reader on every section, and it is the slowest thing on the page by a wide margin. The headline list, the counters and the per-request markers around it still have to be rendered fresh every time, so the page as a whole cannot be cached.

Requirements

Implement:

  • the cached sidebar in app/templates/app/category.html

Only that template changes. GET /<slug>/ is served by category_page in app/views.py, which is given and hands the template everything it needs:

In the contextWhat it is
categorythe Category being shown
category_slugthat category's slug, the value the sidebar varies on
articlesthe section's published articles, newest first
request_seriala number that is different on every request the process serves
fragment_secondssettings.TRENDING_FRAGMENT_SECONDS, the window below

The expensive job is compute_trending in app/trending.py, and it is given. You never call it yourself and you never reimplement it: the template reaches it through {% trending_articles category_slug as trending %}, a tag from the given trending_tags library that the starter template already loads and already calls inside the sidebar. Every run of that job appends one entry to app.trending.CALLS, and the tests read that list, because a cache hit is a run that did not happen and counting runs is the only way to see one. TRENDING_FRAGMENT_SECONDS is 2 in project/settings.py, and CACHES is configured there too with a process-local backend, so there is nothing to install or start.

1. The sidebar, and nothing else, is cached

  • The <aside id="trending-sidebar"> element ends up inside a cached template fragment, with the {% trending_articles %} call still inside that block rather than in front of it.
  • Within the window, repeat requests for the same section serve the stored sidebar and the trending job does not run again, so CALLS grows by one for two back-to-back requests.
  • The sidebar still shows the given ranking: the trending-item entries are the job's order, hottest first, and an unpublished article never appears among them.

2. The window

  • The block's window is fragment_seconds, the value the view passes from the setting, rather than a number written into the template.
  • Once those seconds have passed the next request renders the sidebar again, and the sidebar it renders is the same ranking as before.

3. The fragment name and what it varies on

  • The fragment is named trending_sidebar, written bare in the tag. The name is taken literally, so quotes around it become part of the name and the entry is then filed somewhere the tests do not look.
  • The block varies on the category slug, so after a visit to /technology/ there is an entry for the trending_sidebar fragment varying on technology and nothing yet for science.
  • Two sections are therefore two entries that coexist: visiting each one costs one render, Science is never served Technology's sidebar, and a second visit to each recomputes neither.

4. The rest of the page stays live

  • Everything outside the sidebar is rendered for every request. request_serial differs between two requests made back to back, even while both are being served the same cached sidebar.
  • The latest list keeps rendering too: the article-item entries are the section's published articles, newest first, on the second request as much as the first.

Notes

  • The fragment tag comes from a library the template has to load, and it takes the window first, the fragment name second, and any number of values to vary on after that.
  • Anything that must stay current belongs outside the block, and any call whose result must be current belongs inside it. A block whose expensive call sits in front of it caches the markup and runs the job anyway.
  • Vary on something that changes per request and every request misses, which is slower than not caching at all.
  • Cache the sidebar only. Do not cache the page, the view or the response, and do not reach for cache_page.
  • Do not import compute_trending and do not write your own ranking.
  • A {# ... #} comment works on one line only, so use {% comment %} and {% endcomment %} for anything longer.

More in Caching

See the module
Cached Expensive ViewThe sales report page folds every sale row together on every single hit, although the table it reads changes a few times a day at most. Cache the whole page response for the defined window so a repeat request inside it never runs the aggregation, the first request after it does, and each query string keeps its own entry.—No data yetmediumLow-Level Cache AsideOne hot price lookup hammers the database from two different pages, and each caller either invented its own caching or did without. Centralize the lookup in a cache-aside helper that reads the cache, computes and stores on a miss under the documented key and timeout, and drops a product's entry whenever a price change or a delete makes it wrong.—No data yetmediumLayered Store CachingThe storefront caches nothing: the product page rebuilds itself on every hit, the catalogue pays for every product's facts on every render, and a price change walks away leaving the figures it just made wrong on display. Put a page cache on the product page, a cache-aside helper behind every facts read and a cached fragment around each trending row, all keyed by product id, and make a price change drop exactly that product's three entries.—No data yetmedium

We use cookies that are necessary to run Staffcoder, and optional analytics cookies to see which pages get used. Analytics stays off unless you accept. Read our Cookie Policy.