Evgenij LegotskojJan. 5, 2019, 9:49 a.m.

Django - Tutorial 042. Caching templates for different types of 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.

{% 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.

Content

ADS

This mechanism can be implemented using a mixin.

class EInterfaceMixin:
    TEMPLATE_FULL = 'full.html'     # путь к шаблону
    template_full = None            # pattern caching variable

    # 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
    # request context is required to provide rendering functionality that is dependent on the current user
    @classmethod
    def __render_template_full(cls, obj, request_context):
        if not cls.template_full:
            cls.template_full = loader.get_template(cls.TEMPLATE_FULL)
        return cls.template_full.render({'object': obj, 'user': request_context['user']})

    # method to render using context
    def render_template_full(self, request_context):
        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.

@register.simple_tag(takes_context=True)
def render_template_full(context, obj):
    if obj:
        return obj.render_template_full(context)
    return ''

Use in template

{% load render_template_full from core %}
{% for object in object_list %}
    {% render_template_full object %}
{% 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

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.
Support the author Donate

Comments

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

Let me recommend you the excellent hosting on which EVILEG is located.

For many years, Timeweb has been proving his stability.

For projects on Django I recommend VDS hosting

View Hosting
y

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

  • Result:50points,
  • Rating points-4
n

C++ - Test 005. Structures and Classes

  • Result:41points,
  • Rating points-8
s

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

  • Result:42points,
  • Rating points-8
Popular publications in the last 90 Days
Last comments
f
  • fryn3
  • Oct. 21, 2021, 5:24 a.m.

QML - Tutorial 038. Using the clip property to crop child objects inside Item or Rectangle

Зачем внутри OpacityMask Item, почему сразу Rectangle не вставить? И что за rect.adapt? Мое предложение: layer.enabled: true layer.effect: OpacityMask { …
s

Qt/C++ - Lesson 060. Configuring the appearance of the application in runtime

Добрый вечер, на "лету" не работает, только перезапуск
s

Qt/C++ - Lesson 060. Configuring the appearance of the application in runtime

Спасибо, завтра опробую и отпишусь по результату

Django - Tutorial 007. Adding Pagination based on django-bootstrap3

Просто список каких-нибудь объектов передавайте, который дёрнули ищ api стороннего сервера from django.core.paginator import Paginatorobjects = ['john', 'paul', 'george', 'ringo']p = Pagina…
b

PyQt5 - Tutorial 009. Using QThread with MoveToThread

Спасибо большое
Now discuss on the forum
o

Применение стилей *.qss к собственным виджетам.

или взять код отсюда пример переписать его под свои нужды
j
  • juvf
  • Oct. 21, 2021, 7:31 a.m.

Qt Quick Virtual Keyboard

В QtCreator есть пример на QML с виртуальной клавиатурой "Qt Quick Virtual Keyboard - Basic Example". Собрал, работает. Собрал свой хеловорд свою программу состоящую из главного окна …

QScrollArea dynamically add QCheckBoxes

Всё правильно. Это просто спамер, который отправился в вечный бан.
  • Nomad
  • Oct. 15, 2021, 6:39 a.m.

Вопрос из раздела "как реализовать"

Всем привет. Есть бизнес логика которую надо реализовать на джанге, она состоит в следующем: надо реализовать функционал регистрации/авторизации компаний у которого есть свой дашборд …

Проблема с созданием файлов перевода для составного проекта

Я имею ввиду, если у вас был старые ts файлы, то написать парсер, который составил бы словарь переводов. Например. "Hello world" - "Привет мир" "Hello dev" - "Привет dev" и…
About
Services
© EVILEG 2015-2021
Recommend hosting TIMEWEB