Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tell django to search app's template subfolders

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!

like image 480
Clash Avatar asked Apr 30 '12 15:04

Clash


2 Answers

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.

like image 164
Bob Vork Avatar answered Sep 22 '22 13:09

Bob Vork


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
like image 29
Chris Pratt Avatar answered Sep 20 '22 13:09

Chris Pratt