Evgenii Legotckoi
Evgenii LegotckoiMarch 19, 2023, 2:09 a.m.

Django - Lesson 060. Speeding up a website with caching templates

One of the ways to significantly speed up the speed of a Django site is to cache both individual parts of the site templates and cache the templates after they are compiled by the site. Therefore, we will study both of these ways to improve the speed of the site, in addition to the way we already know the correct optimization of queries to the Django database . You can still test the effectiveness of improvements using the django-silk battery, which is described in the article on improving database queries.

Now let's look at options for using caching.

Caching parts of templates

In cases where you have generated parts of the templates, such as the footer of the site (Footer) or sidebars (SideBar), then it is possible to use caching of these parts of the site. For example, I not only cached them, but even the site's Navigation Drawer and top navigation bar. This was done because I use url embeddable tags and trans translation tags to generate navigation links, which are a lot of types, and together they add a decent load to the site. Not to mention that I use dynamically configurable widgets (you can read about this in the article on the polymorphic system of dynamic widgets . And it is these widgets that each load can double or even triple the time it takes to generate a site page, and given that the types of widgets can be very different, then it will not be possible to write a reasonably efficient database query.Therefore, it is easiest to code these parts of the site template.

It will look like this

{% load i18n cache %}
{% get_current_language as LANGUAGE_CODE %}
{% cache 6000 sidebar LANGUAGE_CODE %}
  {% load sidebar sidebar_sticky from evileg_widgets %}
  {% sidebar %}
  {% sidebar_sticky %}
{% endcache %}

This code uses the embeddable cache tag, which is passed the cache key sidebar , as well as the language code LANGUAGE_CODE as an additional parameter. Language code is required to support multilingual site.

In this case, with dynamic widgets, an important nuance arises, namely, cache invalidation if the SideBar with dynamic widgets was changed through the site's administrative panel.

So, it's implemented like this:

# -*- coding: utf-8 -*-

from django.conf import settings
from django.core.cache import cache
from django.db import models
from django.core.cache.utils import make_template_fragment_key
from django.db.models.signals import post_save, post_delete
from solo.models import SingletonModel
# Some another imports

class SideBar(SingletonModel):
    # Some code of model

class Widget(models.Model):
    # Some code of model

def invalidate_cache(**kwargs):
    for code, description in settings.LANGUAGES:
        cache.delete(make_template_fragment_key('sidebar', [code]))

post_save.connect(invalidate_cache, sender=SideBar)
post_save.connect(invalidate_cache, sender=Widget)
post_delete.connect(invalidate_cache, sender=Widget)

As you can see from the code, a system of signals is used here, which, by the way, is very similar to the [signals and slots in Qt] system (https://evileg.com/en/post/87/), which I really liked as a Qt developer.

So, this system of signals and slots invalidates the cache if both the SideBar object itself and in one of the widgets have been changed. Moreover, invalidation occurs immediately for all languages. Thus, heavy database queries occur no more than once every 6000 seconds. Which is perfectly acceptable.

Cached template loader

And the next way to improve site performance is to use a cached template loader. The fact is that Django usually looks for templates every time a site page is accessed, but if you set up caching on the template loader, then site performance can double.

For example, after enabling this option, the time for generating some pages of the site decreased from 220-240 ms to 120-130 ms. Of course, this is taking into account many other tweaks to improve performance. However, the result is very good.

And the setting of this functionality is done in the settigns.py file and it should look like this.

        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [ os.path.join(BASE_DIR, 'templates') ],
        'OPTIONS': {
            # some another options
            'loaders': [
                ('django.template.loaders.cached.Loader', [


It is highly recommended to cache parts of the template, even if it's just calls to url or trans tags, in a global perspective, this can affect the quality of your site for search engines. It is not for nothing that there are so many articles on the Internet that say that search engines increase very fast sites in the search results.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!


Only authorized users can post comments.
Please, Log in or Sign up

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:60points,
  • Rating points-1

C++ - Тест 003. Условия и циклы

  • Result:92points,
  • Rating points8
  • dsfs
  • April 26, 2024, 2:56 p.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
Last comments
kmssrFeb. 9, 2024, 5:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVADec. 25, 2023, 9:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
JonnyJoDec. 25, 2023, 7:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
GvozdikDec. 19, 2023, 8:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
George13May 7, 2024, 10:27 a.m.
добавить qlineseries в функции в функции: "GPlotter::addSeries(QString title, QVector &arr)" я вызываю метод setChart(...), я в конструктор передал адрес на QChartView элемент
BlinCTMay 5, 2024, 3:46 p.m.
Написать свой GraphsView Всем привет. В Qt есть давольно старый обьект дял работы с графиками ChartsView и есть в 6.7 новый но очень сырой и со слабым функционалом GraphsView. По этой причине я хочу написать х…
Peter SonMay 4, 2024, 3:57 a.m.
Best Indian Food Restaurant In Cincinnati OH Ready to embark on a gastronomic journey like no other? Join us at App india restaurant and discover why we're renowned as the Best Indian Food Restaurant In Cincinnati OH . Whether y…
Evgenii Legotckoi
Evgenii LegotckoiMay 3, 2024, 12:07 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Добрый день. По моему мнению - да, но то, что будет касаться вызовов к функционалу Андроида, может создать огромные трудности.
IscanderCheApril 30, 2024, 2:22 p.m.
Во Flask рендер шаблона не передаётся в браузер Доброе утро! Имеется вот такой шаблон: <!doctype html><html> <head> <title>{{ title }}</title> <link rel="stylesheet" href="{{ url_…

Follow us in social networks