So I am learning Django at in advanced level. I already know how to include templates from BASE_DIR
where manage.py
is located. However I wanted to know how to locate templates in the specific app in Django.
For example, I have a project named mysite
and an app called polls
.
I then specify the templates directory in settings.py
:
DIRS=[os.path.join(BASE_DIR, "templates")]
However, I do not know how to set a templates directory specific to the polls
app. This is the project structure:
.
├── db.sqlite3
├── manage.py
├── mysite
│ ├── asgi.py
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── polls
│ ├── admin.py
│ ├── apps.py
│ ├── __init__.py
│ ├── migrations
│ │ ├── __init__.py
│ ├── models.py
│ ├── static
│ │ ├── images
│ │ ├── scripts.js
│ │ └── style.css
│ ├── tests.py
│ ├── urls.py
│ └── views.py
└── templates
├── polls
│ └── index.html
└── static
├── images
├── scripts.js
└── style.css
I wanted it to look like this.
.
├── db.sqlite3
├── manage.py
├── mysite
│ ├── asgi.py
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── polls
│ ├── admin.py
│ ├── apps.py
│ ├── __init__.py
│ ├── migrations
│ │ ├── __init__.py
│ ├── models.py
│ ├── static
│ │ ├── images
│ │ ├── scripts.js
│ │ └── style.css
│ ├── templates <- New
│ │ ├── polls
│ | │ ├── index.html
│ ├── tests.py
│ ├── urls.py
│ └── views.py
└── templates
├── polls
│ └── index.html
└── static
├── images
├── scripts.js
└── style.css
If you have the app specific templates located at polls/templates/polls/
, then you need to add that path to TEMPLATES in settings.py
as shown below:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'polls/templates')], # here the app template path is set
'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',
],
},
},
]
And while rendering template the path should have a folder prefix like
render(request, 'polls/index.html', context)
UPDATE: as in above settings APP_DIRS
is set to True
, django will automatically look into <yourapp>/<templates>
directory for the templates even if the app template paths are not explicitly specified.