Django Best Practices: Template Structure
Updated
Table of Contents
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 for a templates folder within each app. 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 a Django project called django_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.
├── django_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
This approach is demonstrated in the official Django polls tutorial and works just fine.
Option 2: Project Level
As Django projects grow, having all the templates in one place is often more convenient than hunting for them within multiple apps. We can do this with a single-line change to our settings.py file.
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": [BASE_DIR / "templates"],
...
},
]
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.
├── django_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
Next Steps
Remember, if you have overridden DIRS in the settings.py file, the Django template loader will first look there and then look to APP_DIRS for an app-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.