Lila25mila
Lila25milaJan. 28, 2019, 1:19 a.m.

Using Jinja2 with Django (since 1.8)

On the Medium Corporation resource, a user named Samu shares his experience using Jinja2.
According to him, he previously used Jinja2 in his projects built with Flask. But then I decided to use Jinja2 with Django for potential performance gains (10-20x faster compared to Django templates) and interaction with Nunjucks.
Samu shares his experience with people who are already familiar with these technologies, and his article is intended to reveal and simplify the steps a little.


If you're just getting started with Django, he recommends starting with a great tutorial at this link . You can also see some simple instructions for Jinja2 from Django here .
So let's get started.

Install and configure Jinja2 first
pip install Jinja2

and don't forget to add it to the needs.txt file. Then add the following templating engine settings to the TEMPLATES variable in settings.py

{
   ‘BACKEND’: ‘django.template.backends.jinja2.Jinja2’,
   ‘DIRS’: [],
   ‘APP_DIRS’: True,
   ‘OPTIONS’: {
     ‘environment’: ‘your-app.jinja2.environment’
   },
 }

So, all template settings look something like this:

TEMPLATES = [
 {
   ‘BACKEND’: ‘django.template.backends.jinja2.Jinja2’,
   ‘DIRS’: [],
   ‘APP_DIRS’: True,
   ‘OPTIONS’: {
     ‘environment’: ‘your-app.jinja2.environment’
   },
 },
 {
   ‘BACKEND’: ‘django.template.backends.django.DjangoTemplates’,
   ‘DIRS’: [],
   ‘APP_DIRS’: True,
   ‘OPTIONS’: {
     ‘context_processors’: [
       ‘django.template.context_processors.debug’,
       ‘django.template.context_processors.request’,
       ‘django.contrib.auth.context_processors.auth’,
       ‘django.contrib.messages.context_processors.messages’,
     ],
   },
 },
]

Don't forget to also change the Jinja2 settings environment variable to the correct app name (change "your-app" to whatever your app folder is called).
The options environment allows us to use certain features in templates that are further customized. Create a jinja2.py file in your application folder (in the same place as the settings.py file) and add the following:

from django.contrib.staticfiles.storage import staticfiles_storage
from django.urls import reverse
from jinja2 import Environment
def environment(**options):
    env = Environment(**options)
    env.globals.update({
        ‘static’: staticfiles_storage.url,
        ‘url’: reverse,
    })
 return env

This allows us to use Django template tags like {% url 'index' %} or {% static 'path / to / static / file.js' %} in our Jinja2 templates. As you can see, these template tags use the actual functionality provided by Django. Following the Jinja2 way of calling functions in a template, you can use them like this:
В Django:

{% url ‘index’ variable %}

which is equivalent in Jinja2:

{{url(‘index’, args=[variable])}}

And for named variables you can use:

{{url('index', kwargs={'variable_key':variable}}}

В Django:

{% static ‘path’ %}

which is equivalent to

{{ static(‘path’)}}

As you've probably already noticed, you can basically add any functionality to the Jinja2 environment by adding it to the jinja2.py file for later use in templates.

Final installation folders

Once you've got your settings right, you can then simply create a Jinja2 folder anywhere you'd like a templates folder to be created. It should work automatically since Django is a pretty good framework. Having both Django and Jinja2 templates allows you the flexibility to use both. For example, you might have a Django admin panel, and various plugins to work with that use Django templates. Be sure to read the Jinja2 documentation to learn more.
Below is an example of what one application folder structure might look like for a project:

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!

Кирилл Порох
  • April 15, 2020, 4:19 a.m.
  • (edited)

У МЕНЯ ОШИБКА


File "C:\Users\даня\Desktop\CODS\Django\imbanamid\first\jinja2.py", line 4, in <module>
    from django.core.urlresolvers import reverse
ModuleNotFoundError: No module named 'django.core.urlresolvers'
Evgenii Legotckoi
  • April 15, 2020, 4:31 a.m.

Выглядит так, что текущая версия jinja2 несовместима с с той версией Django, которую вы используете. По ходу разработчики Jinja2 так до сих пор не обновились.

Эта строчка from django.core.urlresolvers import reverse соответствует старым версия джанго, до версии 2 точно, как обстоит дело с более поздними версиями точно не помню, но на данный момент в последних вторых и третьих версиях джанго используется такой импорт from django.urls import reverse .

В вашем случае есть следующие выходы:

  • Откатить джанго на более раннюю версию
  • Использовать стандартный шаблонизатор или какой-то другой... хотя тут альтернативы практически нет.
  • Убедиться, что вы точно используете последнюю версию jinja и она имеет нормальную совместимость с Django, всё-таки как никак этот шаблонизатор хорошо поддерживается разрабами и полагаю, что у вас просто установилась не самая актуальная версия.
  • Написать bug-request разработчикам jinja
  • Написать исправление и сделать pull-request разработчикам jinja
Кирилл Порох
  • April 15, 2020, 4:42 a.m.

Спасибо, всё заработало!

Evgenii Legotckoi
  • April 15, 2020, 4:43 a.m.

Пожалуйста, а что конкретно сделали? Откатились?

Кирилл Порох
  • April 15, 2020, 5:04 a.m.
  • (edited)

Да,откатился . Неподскажите где найти документацию jinja2 на русском?

Evgenii Legotckoi
  • April 15, 2020, 5:11 a.m.
  • (edited)

К сожалению нет, не подскажу. У меня был интерес к этому шаблонизатору, но так получилось, что мне пришлось бы переписывать очень большую часть проекта, чтобы его внедрить, поэтому я отказался до лучших времён, поскольку трудозатраты не окупились бы на данный момент.
Следовательно я дальше изучения основ не пошёл, поэтому и на русскоязычную документацию не имел возможности натолкнуться.
Но скорее всего полной русскоязычной документации вовсе нет, максимум отдельные статьи на разных ресурсах.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
d
  • dsfs
  • April 26, 2024, 1:56 a.m.

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

  • Result:80points,
  • Rating points4
d
  • dsfs
  • April 26, 2024, 1:45 a.m.

C++ - Test 002. Constants

  • Result:50points,
  • Rating points-4
d
  • dsfs
  • April 26, 2024, 1:35 a.m.

C++ - Test 001. The first program and data types

  • Result:73points,
  • Rating points1
Last comments
k
kmssrFeb. 8, 2024, 3:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 7:30 a.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 5:38 a.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 18, 2023, 6:01 p.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
G
GarApril 22, 2024, 2:46 a.m.
Clipboard Как скопировать окно целиком в clipb?
DA
Dr Gangil AcademicsApril 20, 2024, 4:45 a.m.
Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
a
a_vlasovApril 14, 2024, 3:41 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 13, 2024, 11:35 p.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 1:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks