Evgenii Legotckoi
Jan. 5, 2019, 8:49 p.m.

Django - Tutorial 042. Caching templates for different types of content

Content

In Django - Lesson 035. Different templates for rendering different types of content in search results it was shown how to render different templates depending on what type of content drawn in the search results on the site. In this case, the key point was that it was not necessary to make the verification conditions for the selection of the template. The information about the balbalon was stored in the variable TEMPLATE_PREVIEW, through which the template was inserted into the include tag in the Django template.

  1. {% include object.TEMPLATE_PREVIEW %}

In this method there is one big drawback. The fact is that the include tag with each of its calls is looking for a template. With a large load on the site - this can significantly increase the duration of the response from the server. To solve this problem, you need to somehow cache the pattern. Since different types of content use different templates, to do this using inclusion_tag is quite problematic.

This problem was solved by caching the template at the class level as a class variable.


This mechanism can be implemented using a mixin.

  1. class EInterfaceMixin:
  2. TEMPLATE_FULL = 'full.html' # путь к шаблону
  3. template_full = None # pattern caching variable
  4.  
  5. # we will cache with the help of the class method, in which we pass the object for rendering, as well as the context of the request
  6. # request context is required to provide rendering functionality that is dependent on the current user
  7. @classmethod
  8. def __render_template_full(cls, obj, request_context):
  9. if not cls.template_full:
  10. cls.template_full = loader.get_template(cls.TEMPLATE_FULL)
  11. return cls.template_full.render({'object': obj, 'user': request_context['user']})
  12.  
  13. # method to render using context
  14. def render_template_full(self, request_context):
  15. return self.__render_template_full(self, request_context)

Next you need to register the built-in tag. This is necessary so that when rendering in a template, pick up the context of the request. In my case, part of the templates can not be correctly displayed without information about the current user who is on the site.

  1. @register.simple_tag(takes_context=True)
  2. def render_template_full(context, obj):
  3. if obj:
  4. return obj.render_template_full(context)
  5. return ''

Use in template

  1. {% load render_template_full from core %}
  2. {% for object in object_list %}
  3. {% render_template_full object %}
  4. {% empty %}

Conclusion

This mixin can be added to all models that will use this rendering engine.

The first time the class method is called, the template will be cached. In subsequent render calls, the already cached template will be used. Thus, there will be no useless CPU time spent on searching for a template with each call of the include tag

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html