If you want to override a template coming with an app in django (in app/templates/app/) you create a template of the same name in another directory, which the template loader checks before the app's template dir. If you just want to override certain blocks of the template you also have to copy the whole template and change that block, which is actually not very DRY.
Does anybody know a way to override the orginial template, while at the same moment extending it, so that you just have to override the specific block you want to change? (the thing is doing this without changing the template's name, because in some cases you might have to change the view to make it work with another template)
EDIT: As Adam Taylor pointed out in the comments from Django 1.9 on this is possible without any hacks.
To do so, you will have to change the project's settings.py . Find the TEMPLATES section and modify accordingly. To override the default template you first need to access the template you want to modify from the django/contrib/admin/templates/admin directory.
Use Django extends in multiple templates html to multiple HTML documents using the same document structure and DTL block content tags. This means the header can render in multiple templates.
Extends sort of 'includes' the parent template and then can overwrite parts of it for different functionality. Include does a simple include rendering a template in a current context.
From the documentation: {% extends variable %} uses the value of variable. If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template.
I think the answer from this related question is pertinent; currently, the best solution seems to be to use a custom template loader from the django-apptemplates package on PyPI, so you can just use pip to install it (e.g. pip install django-apptemplates
).
The template loader allows you to extend a template in a specific app; for example, to extend the index page of the admin inteface, you would add
'apptemplates.Loader',
to your TEMPLATE_LOADERS
list in settings.py
, and use
{% extends "admin:admin/index.html" %}
in your templates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With