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, DIRSis 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:

  1. import os
  2.  
  3. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  4.  
  5. INSTALLED_APPS = [
  6. ...,
  7. 'blog',
  8. ...,
  9. ]
  10.  
  11. TEMPLATES = [
  12. {
  13. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  14. 'DIRS': [os.path.join(BASE_DIR, 'templates')],
  15. 'APP_DIRS': True,
  16. ...
  17. },
  18. ]

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:

  1. templates/
  2. blog/
  3. list.html
  4. 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:

  1. TEMPLATES = [
  2. {
  3. ...,
  4. 'APP_DIRS': True,
  5. ...
  6. },
  7. ]

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:

  1. myapp/
  2. templates/
  3. blog/
  4. list.html
  5. post.html

With APP_DIRS set to True, the templateloader will look in the app’s templates directory and find the templates.