The default project layout created by the startproject command does not define a location for your templates. This is very easy to configure.
Create a directory named templates in your project's root directory. Specify the value for DIRS inside the TEMPLATES variable in your settings.py: (can be found within superbook/settings/base.py in our superbook project)
BASE_DIR = os.path.dirname(os.path.dirname(__file__)) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, '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', ], }, }, ]
That's all. For example, you can add a template called about.html and refer to it in the urls.py file as follows:
urlpatterns = [
path('about/', TemplateView.as_view(template_name='about.html'),
name='about'),
Your templates can also reside within your apps (if APP_DIRS is true). Creating a templates directory inside your app directory is ideal to store your app-specific templates.
Here are some good practices to organize your templates:
- Keep all app-specific templates inside the app's template directory within a separate directory, for example projroot/app/templates/app/template.html— notice how app appears twice in the path
- Use the .html extension for your templates
- Prefix an underscore for templates, which are snippets to be included, for example: _navbar.html
The order of specifying template directories matters a lot. To better appreciate that, you need to understand how templates are rendered in Django.