Overriding templates
In your project, you might want to override a template in another Djangoapplication, whether it be a third-party application or a contrib applicationsuch as django.contrib.admin
. You can either put template overrides in yourproject’s templates directory or in an application’s templates directory.
If you have app and project templates directories that both contain overrides,the default Django template loader will try to load the template from theproject-level directory first. In other words, DIRS
is searched before APP_DIRS
.
See also
Read Overriding built-in widget templates if you’re looking todo that.
Overriding from the project’s templates directory
First, we’ll explore overriding templates by creating replacement templates inyour project’s templates directory.
Let’s say you’re trying to override the templates for a third-party applicationcalled blog
, which provides the templates blog/post.html
andblog/list.html
. The relevant settings for your project would look like:
- import os
- BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
- INSTALLED_APPS = [
- ...,
- 'blog',
- ...,
- ]
- TEMPLATES = [
- {
- 'BACKEND': 'django.template.backends.django.DjangoTemplates',
- 'DIRS': [os.path.join(BASE_DIR, 'templates')],
- 'APP_DIRS': True,
- ...
- },
- ]
The TEMPLATES
setting and BASE_DIR
will already exist if youcreated your project using the default project template. The setting that needsto be modified is DIRS
.
These settings assume you have a templates
directory in the root of yourproject. To override the templates for the blog
app, create a folderin the templates
directory, and add the template files to that folder:
- templates/
- blog/
- list.html
- post.html
The template loader first looks for templates in the DIRS
directory. Whenthe views in the blog
app ask for the blog/post.html
andblog/list.html
templates, the loader will return the files you just created.
Overriding from an app’s template directory
Since you’re overriding templates located outside of one of your project’sapps, it’s more common to use the first method and put template overrides in aproject’s templates folder. If you prefer, however, it’s also possible to putthe overrides in an app’s template directory.
First, make sure your template settings are checking inside app directories:
- TEMPLATES = [
- {
- ...,
- 'APP_DIRS': True,
- ...
- },
- ]
If you want to put the template overrides in an app called myapp
and thetemplates to override are named blog/list.html
and blog/post.html
,then your directory structure will look like:
- myapp/
- templates/
- blog/
- list.html
- post.html
With APP_DIRS
set to True
, the templateloader will look in the app’s templates directory and find the templates.