Sobes.tech
Junior — Middle

Explain the principle of template caching in Django and its advantages.

sobes.tech AI

Answer from AI

In Django, template caching allows storing the generated HTML code of a template or its parts in cache, so that subsequent requests do not need to re-render. This speeds up page delivery and reduces server load.

How it works:

  • The {% cache %} tag is used in templates, which takes a cache key and lifetime.
  • On first render, the result is stored in cache.
  • On subsequent requests, if the cache has not expired, Django returns the stored HTML without re-rendering.

Advantages:

  • Faster response due to reduced computations.
  • Lower load on database and server.
  • Flexibility: can cache entire pages or individual fragments.

Example:

{% load cache %}

{% cache 600 sidebar user.id %}
  <!-- complex block that rarely changes -->
  <div>Hello, {{ user.username }}!</div>
{% endcache %}

Here, the block is cached for 600 seconds with a key depending on user.id.