- Author:
- Krzysiek555
- Posted:
- August 28, 2021
- Language:
- Python
- Version:
- 3.0
- Score:
- 0 (after 0 ratings)
This is an updated of version snippets:
Tested to with with Django 3.2
With this template loader you can extend templates from built-in Django apps such as Django admin.
Example:
{% extends "admin:admin/index.html" %}
{% block sidebar %}
{{block.super}}
<div>
< h1>Statistics< /h1>
< a href="/admin/station/stats/">Published Stations< /a>
</div>
{% endblock %}
Configuration:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
'your_app/templates'
],
'OPTIONS': {
# (...)
# See: https://docs.djangoproject.com/en/3.2/ref/templates/api/#django.template.loaders.cached.Loader
'loaders': [
('django.template.loaders.cached.Loader', [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
'your_app.template_loaders.SpecificAppTemplateLoader',
]),
],
},
},
]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | import io
from os.path import join, abspath
from typing import Generator
from django.apps import apps
from django.template import TemplateDoesNotExist, Origin
from django.template.loaders.base import Loader as BaseLoader
class SpecificAppTemplateLoader(BaseLoader):
def get_template_sources(self, app_template_name: str) -> Generator[Origin, None, None]:
template_parts = app_template_name.split(':', 1)
if len(template_parts) != 2:
raise TemplateDoesNotExist(app_template_name)
app_name, template_name = template_parts
app_dir = apps.get_app_config(app_name).path
template_dir = abspath(join(app_dir, 'templates'))
template_path = join(template_dir, template_name)
yield Origin(
name=template_path,
template_name=template_name,
loader=self,
)
def get_contents(self, origin: Origin) -> str:
try:
with io.open(origin.name, encoding=self.engine.file_charset) as fp:
return fp.read()
except IOError:
pass
raise TemplateDoesNotExist(f'Could not read template content: {origin}')
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.