Join my Asyncio(Python) course on Udemy 👀

Use one directory for HTML templates in Django

April 17, 2021  ‐ 1 min read

From which directory Django loads HTML templates is configured with the TEMPLATES variable in settings.py. When you create a fresh Django application TEMPLATES is configured to look for a templates folder in the apps you create to load HTML templates from.

Where Django apps are supposed to be pretty self-containing, my experience is that I have quite some overlap in HTML components on the template side between apps. Think of some shared layouts or generic partials for lists for example.

Therefore I prefer a templates directory outside my apps for some projects. You can configure this by settings 'DIRS' in the TEMPLATES setting. The following example shows how to configure Django so that it will look for templates in a templates directory in the project root.

The example sets 'APP_DIRS' to False so Django won't look for templates in apps. You can keep this set to True as well if you prefer.

# settings.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, 'templates')
        ],
        'APP_DIRS': False,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]