Beyond the SQL: Cacheing: Page cacheing

  1. Cacheing
  2. Template tag cacheing

The easiest way to set up cacheing is to just tell Django to cache every page. You can do this by adding a cacheing “middleware”. Look for MIDDLEWARE_CLASSES in settings.py. “Middleware” is a low-level “plugin” system for altering page requests; that includes things like providing a cached version of a page instead of recreating it for every request.

We need a middleware at the very beginning of the list, and a middleware at the very end. Change MIDDLEWARE_CLASSES to:

MIDDLEWARE_CLASSES = (

'django.middleware.cache.UpdateCacheMiddleware',

'django.middleware.common.CommonMiddleware',

'django.contrib.sessions.middleware.SessionMiddleware',

'django.contrib.auth.middleware.AuthenticationMiddleware',

'django.middleware.cache.FetchFromCacheMiddleware',

)

Also, add this line below that:

CACHE_MIDDLEWARE_SECONDS = 120

That’s the number of seconds that full pages should be cached.

Your pages will now be cached for two minutes. You can test this by making a change in one of your posts immediately after viewing the public version; the public version will not immediately change, but if you wait two minutes, it will change.

  1. Cacheing
  2. Template tag cacheing