Django Best Practices - Template Structure

Will Vincent - Feb 21 '20 - - Dev Community

There are two main ways to organize your template structure in Django: the default app-level way and a custom project-level approach.

Option 1: App Level

By default the Django template loader will look within each app for a templates folder. But to avoid namespace issues you also need to repeat the app name in a folder below that before adding your template file.

For example, if we had an example_project with a pages app and a home.html template file, the proper structure would be like this: within the pages app we create a templates directory, then a pages directory, and finally our 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
Enter fullscreen mode Exit fullscreen mode

This is demonstrated in the official Django polls tutorial and works just fine.

Option 2: Project Level

As a Django projects grow in size it's often more convenient to have all the templates in one place rather than hunting for them within multiple apps. With a single line change to our settings.py file, we can do this.

Update the 'DIRS' config under TEMPLATES as follows, which specifies that in addition to looking for an app-level templates directory, the Django template loader should also look for a project-level templates directory.

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

Then create a templates directory at the same level as the project. Here's an example of what it would look like with 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
    ├── home.html
└── manage.py
Enter fullscreen mode Exit fullscreen mode

Next Steps

Remember the Django template loader will look for an app-level templates directory and then--if we update the DIRS setting--it will also look for a project-level templates directory. There is no "right" way to organize templates within your Django project but many developers, myself included, prefer the project-level approach.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .