Template structure in Django

There are two main ways to organize Django's template structure: application-level and custom, project-level, which is specified in setting.py.

Application level

By default, the Django template loader looks for the templates directory in each application (this is the responsibility of the APP_DIRS parameter in the project settings). To avoid namespace confusion, it is also recommended to create another subdirectory in this directory, named the same as the application.

For example, we have a example_project project with an pages application and a home.html template file, then the correct structure would look like this: in the pages application we create a templates directory, and in it a pages directory in which we place the home.html:

file.

├── example_project
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
|   └── pages
|      ├── __init__.py
│      ├── admin.py
│      ├── apps.py
│      ├── models.py
│      ├── tests.py
│      └── views.py
|      ├── templates
|          ├── pages
|              ├── home.html
└── manage.py

Project Level

As a Django project grows, it is often preferable to store all templates in one place rather than spreading them across all applications. You can do this by customizing the settings.py.

Update parameter 'DIRS' in parameter TEMPLATES where we specify, in addition to searching for templates in application catalogs, searching for templates in a separate project-level catalog.

# settings.py
TEMPLATES = [
    {
        ...
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        ...
    },
]

Now let's create the templates directory in the project directory. Now the structure of our project will look like this:

├── example_project
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
|   └── pages
|      ├── __init__.py
│      ├── admin.py
│      ├── apps.py
│      ├── models.py
│      ├── tests.py
│      └── views.py
├── templates
    ├── home.html
└── manage.py

Closure

Remember that the template loader first looks for them in applications, and then, if configured DIRS, in the templates project directory. This is not exactly the "right" way to organize templates, but most developers, including the author, prefer to use templates at the project level.

For myself, I would like to add that you can use a common directory for templates that are not application-specific or are used by many applications in a project. For example, a base template base.html, which is then inherited by other templates.

Back to Top