Hello,
I am trying to set a root directory for my templates on top of the app directories. The idea would be to have a base directory from which apps can extend the templates as desired.
Here is my templates settings in project_name/project_name/settings.py :
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
},
]
when looking at the template loading, I see in the error message that django is trying to load templates from :
c:\Users\User\project_name\app_name\templates\project_name\base.html (Source does not exist)
i don’t undersand the second project_name because it shoud be app_name. I checked, the app in question has a name defined in its apps.py. Any idea what I am doing wrong ?
For that “root directory” to work, you need to set it within “DIRS” list, something like:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "templates")], # This should produce a "c:\Users\User\project_name\templates" path
'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',
],
},
},
]
1 Like
Hello,
Thanks for the answer. Indeed, I need this.
But at the moment, I first want to understand why django is calling a directory called “project_name” for my “app_name” rather than “app_name” as foreseen :
c:\Users\User\project_name\app_name\templates\project_name\base.html
should be
c:\Users\User\project_name\app_name\templates\app_name\base.html
Calling from where? Please show how you’re trying to load a template.
1 Like
from project_name/app_name/views.py :
class myView(ListView):
[...]
template_name = "app_name/index.html"
Ok, but your error is about “base.html”, so I assume your index.html
file should have the {% extend ... %}
tag at the top, could you show it?
1 Like
You are correct. The issue must come from there :
{% extends “project_name/base.html” %}
So here you are, in your case, project_name/base.html
tells Django that project_name
is the name of the app, that’s why it looks for a template at: c:\Users\User\project_name\app_name\templates\project_name\base.html
.
You don’t need to use a project_name
in a template path. If you want to load a template file from the top level directory i.e. root, just call it by its name:
{% extends “base.html” %}
Hope this helps
1 Like
It’s right on spot. Thank you very much for your help and your time !
no problem, you’re welcome!