I have the following folder structure for the templates on my django app:
templates/
app/
model1/
model1_form.html
model2/
model2_form.html
Suppose I'm using model1 and a generic ListView, right now it only searches at templates/app/model1_form.html. Is there anyway I can tell django he should also search the app/ subfolders? I don't want to have to set the template name and path manually (template_name="templates/app/model1/model1_form.html"
).
At settings.py I have:
import os.path
BASE_PATH = os.path.dirname(os.path.dirname(__file__))
TEMPLATE_DIRS = (
BASE_PATH+'/templates/',
)
This is my view:
class HousesListView(ListView):
model = House
context_object_name = "house_list"
Thanks in advance!
The other answers were correct at the time, but for anyone coming across this now, this is how this is done in Django 1.8+
By default, Django now looks in app folders for templates. This is indicated by 'APP_DIRS': True,
in the TEMPLATES
setting like this:
TEMPLATES = [
{
...
'DIRS': ['templates'],
'APP_DIRS': True,
...
},
]
As the other answers indicate, you should still use appname/templates/appname/model1_form.html
to namespace the templates
( more info: https://docs.djangoproject.com/en/1.8/intro/tutorial03/#write-views-that-actually-do-something in the box titled 'template namespacing')
Final check: make sure the app you're using is in the INSTALLED_APPS
tuple, as that was the problem I was having.
You need to add django.template.loaders.app_directories.Loader
to TEMPLATE_LOADERS
(if it's not already).
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
Then, change your folder structure such that you have a "templates" folder in the app directory:
- <project_root>
- app
- templates
- model1
- model2
Or to properly namespace the models so they don't clash with other app names accidentally:
- <project_root>
- app
- templates
- app
- model1
- model2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With