I am using Django with Jinja2.
I have an issue where the Jinja2 template engine is not rendering templates on my local machine/Docker setup but the same code does render using Jinja2 on Github Codespaces.
The specific error is:
TemplateSyntaxError at /val/
Could not parse the remainder: '('valapp:engindex', args=[engagement.id])' from 'url('valapp:engindex', args=[engagement.id])'
My template settings in the settings.py file are:
TEMPLATES = [
{
"BACKEND": "django_jinja.backend.Jinja2",
"DIRS": [
os.path.join(BASE_DIR, 'templates')
],
"APP_DIRS": True,
"OPTIONS": {
"environment": 'valuation.jinja2.environment',
}
},
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'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',
],
},
},
]
I also have a jinja2.py file with the following code:
from django.contrib.staticfiles.storage import staticfiles_storage
from django.urls import reverse
from crispy_forms.utils import render_crispy_form
import os
from jinja2 import Environment, FileSystemLoader
custom_template_dir = "/workspaces/valapp/valapp/templates"
def environment(**options):
env = Environment(**options)
env.globals.update({
'static': staticfiles_storage.url,
'crispy': render_crispy_form,
'url': reverse,
})
env.loader = FileSystemLoader(custom_template_dir)
return env
My requirements.txt file has the following:
asgiref==3.6.0
Django==4.1.7
pytz==2022.7.1
sqlparse==0.4.4
crispy-bootstrap4==2022.1
django-crispy-forms==2.0
django-jinja==2.10.2
Jinja2==3.1.2
psycopg2==2.9.5
click==8.1.3
reportlab==3.6.12
The Dockerfile has:
FROM python:3.10.11-alpine3.17
WORKDIR /app
COPY requirements.txt requirements.txt
RUN apk update
RUN apk add postgresql-dev gcc python3-dev musl-dev
RUN apk add --no-cache freetype-dev
RUN pip3 install -r requirements.txt
COPY . .
CMD ["python3", "manage.py", "runserver", "0.0.0.0:8000"]
I don’t understand why Django is using the Django template engine on my local/Docker setup but Jinja2 on Github Codespaces. Any guidance is much appreciated.
2
Answers
I figured it out:
in the jinja2.py file, an absolute path was set:
I removed that and the env.loader and Jinja2 worked again.
Django is using the
Django
template engine instead ofJinja2
, lets try to change the order in theTEMPLATES
setting to putDjango
beforeJinja2
. You will also have to check thatJinja2
templates are differentiated by their file extension .jinja , otherwise Django cant differentiate them.