I know that they don't do this, but for one of my pet-projects I want a strange thing: store jinja-templates in the database (and be able to edit them through the admin panel).
There is something like this model (in models.py):
class TbTemplate(models.Model):
szFileName = models.CharField(
primary_key=True,
db_index=True,
unique=True,
verbose_name="Path/Name"
)
szJinjaCode = models.TextField(
verbose_name='Template',
help_text='Template Code (jinja2)'
)
szDescription = models.CharField(
max_length=100,
verbose_name='Description'
)
def __unicode__(self):
return f"{self.szFileName} ({self.szDescription})"
def __str__(self):
return self.__unicode__()
class Meta:
verbose_name = '[…Template]'
verbose_name_plural = '[…Templates]'
Next, in view.py you can do something like this:
# -*- coding: utf-8 -*-
from django.http import HttpRequest, HttpResponse
from django.template.loader import render_to_string
from web.models import TbTemplate
def something(request: HttpRequest, template: str) -> HttpResponse:
"""
:param request: http-in
:param template: Template name
:return response: http-out
"""
to_template = {}
# ...
# ... do smth
# ...
tmpl = TbTemplate.objects.get(pk=template)
html = render_to_string(tmpl.szJinjaCode, to_template)
return HttpResponse(html)
And everything works. Templates to available for editing through the admin panel (of course, you need to hang a "mirror"-like widget for syntax highlighting, etc.)...
But I want to use in jinja templates like: {% include "something_template.jinja2" %} ... And for this it is necessary that the templates are not only in the database, but also stored as files in the templates-folder.
In addition, templates are easier to create and edit in IDEs, and access to templates through the admin panel only for cosmetic changes.
And then I need to somehow intercept the "read" method in/for the admin panel. So that if a template in the TbTemplate table is opened for editing in the admin panel, then for the szJinjaCode it was read not from the database, but from the corresponding szFileName-file.
How to do this?