Add template folders from each app created via startapp

python manage.py startapp application
python manage.py startapp customers
D:\projectName\APPLICATION
├───migrations
│   └───__pycache__
├───templates
│   ├───auth
│   └───includes
└───__pycache__


D:\projectName\CUSTOMERS
├───migrations
│   └───__pycache__
├───templates
└───__pycache__

In both templates there is an index.html - In CUSTOMERS also there is an index.html in templates folder.

customers\urls.py

from customers import views
from django.urls import path

urlpatterns = [
    path('', views.index),
]

In projectName’s settings.py :

path('', views.index, name='index'),
path('customers/', include('customers.urls'))

But in my customers/views.py I have to do :

return render(request, '../../customers/templates/index.html')

because return render(request, 'index.html') is returning application/templates/index.html

How can I add template folders from each app to 'DIRS': [BASE_DIR / 'templates'] in Django 4.1 ?

You should definitely namespace your templates. I did not found this on the docs, but there’s one point that says it.
So namespacing a template would be:
app1/templates/app1/index.html instead of app1/templates/index.html. The same applies for others apps. By doing this you then can render your templates like: app1/index.html

Actually, i found it on the docs.
Take a look on the green box at the end of that section

1 Like

Additionally, even with the templates being properly namespaced, you want to make sure that your TEMPLATES settings contains the APP_DIRS: True attribute.

2 Likes

APP_DIRS: True is there by default in Django 4.1.

To actually get this working I had to do :
customers\templates\customers.index.html

Even customers\templates\customers\index.html won’t make it. It’ll still pull from applications\templates\index.html

I hope there is way to auto-detect this in the future versions.

Other options is to put all templates in D:\projectName\templates

Correct. That’s the wrong reference to put in the render call.

With APP_DIRS: True, the reference would just be to customers/index.html

I’m not sure what you’re looking for it to autodetect. It works exactly as designed and intended.

It isn’t. Its taking in index.html from application/templates/index.html

It seems to look for the first location of index.html

No, that is either not accurate or not complete.

If

  • your TEMPLATES settings includes APP_DIRS: True
    and
  • the index.html is in the location project/customers/templates/customers/index.html,
    and
  • you do not have an index.html in project/templates/customers/index.html,

then render(request, 'customers/index.html') will render the index.html in project/customers/templates/customers.

If it is not, then you have something wrong.

1 Like