28

I have a project with 2 apps

project/
    blog/
        templates/
            index.html
    polls/
        templates/
            index.html
    project/
        templates/
            base.html
            index.html

Now i want that the two apps extends the projects base.html. Is this the way to go? how it is possible and are there better solutions?

There is already an question which is handling this question, but it's only worth mentioning if you dont use split directories: Django project base template

tl;dr: I want to use split directories and want to know how to extend a base template from multiple apps without copying it to every app

Community
  • 1
  • 1
fechnert
  • 1,215
  • 2
  • 12
  • 30
  • This has been answered [here](https://stackoverflow.com/questions/14720464/django-project-base-template/60931532#60931532) – mukesh.kumar Mar 30 '20 at 13:30

3 Answers3

50

In current Django (1.10) TEMPLATE_DIRS is deprecated, so:

  1. Add a templates directory at the project root,
  2. In settings.py find TEMPLATES -> DIRS and add it like this:

    TEMPLATES = [
    {
        ...
        'DIRS': [(os.path.join(BASE_DIR, 'templates')),],
        ...
    }
    
  3. Add a base.html to that directory.

  4. Extend it wherever you want using {% extends 'base.html' %}
Oliver Sosa
  • 754
  • 9
  • 16
  • 1
    Thanks for the tip! Not sure when this changed, but `BASE_DIR` is a `pathlib.Path` object, so you could write `BASE_DIR / "templates"` instead of using `os.path.join`. – Nico Bako Dec 23 '21 at 15:45
8
  1. Add a templates directory at the project root, and add it to your TEMPLATE_DIRS setting.
  2. Add a base.html to that directory.
  3. Extend it wherever you want using {% extends 'base.html' %}
rnevius
  • 26,578
  • 10
  • 58
  • 86
3

For Django versions above 1.8 the upgrade doc suggests the vanilla settings (for most non-advanced django tangoers like me) be added to your settings.py:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [(os.path.join(BASE_DIR, 'my_Templates_Directory')),],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                # Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this
                # list if you haven't customized them:
                'django.contrib.auth.context_processors.auth',
                'django.template.context_processors.debug',
                'django.template.context_processors.i18n',
                'django.template.context_processors.media',
                'django.template.context_processors.static',
                'django.template.context_processors.tz',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Both BACKEND and OPTIONS were required, otherwise I had errors relating to 'INVALID BACKEND' and 'django.contrib.auth.context_processors.auth' must be in TEMPLATES'.

NullPumpkinException
  • 1,396
  • 1
  • 18
  • 22