Search code examples
pythondjangodjango-templatessatchmo

How can I fix my template loader to check for the root directory?


I have a directory structure like this if it matters (it's the default recommended structure as per satchmo documentation):

site
- apps
   | - __init__.py
- config
- projects
   | - site
        | - home
             | - templates
                  | - about.html
                  | - home.html
             | - models.py, views.py, admin.py
        | - __init__.py
        | - local_settings.py
        | - settings.py
        | - urls.py
        | - wsgi.py
   | - __init__.py
- static
   | - css
   | - images (maybe this got autogenerated?)
   | - js
   | - media
- templates
   | base.html
- manage.py

My URLs have entries for the about.html and home.html and both of those extend base.html. However, when I visit the URLs, I get the generic satchmo page with some of my text that I had included from about and home, but it did not extend base.html at all. Before I installed satchmo, I could confirm that this was working, but now I'm not sure what went wrong. I'm assuming that it's extending some other base.html instead because if I change my extends to master.html instead, it throws a TemplateDoesNotExist exception (which I'm also unsure of how to resolve). I have the following in my settings.py:

TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
)

TEMPLATE_DIRS = (
    'templates',
)

If I move the templates directory to the site folder within projects, it seems to work, but I don't want it there. I tried adding '../../templates' to TEMPLATE_DIRS, but that doesn't work either, and even if it did, I'm not sure how that would interact for templates that I declare under some levels of the app folder. What's the correct way to fix this?


Solution

  • TEMPLATE_DIRS entries should be absolute paths. You can do something like this:

    import os
    from os.path import normpath, abspath, dirname, join
    BASE_DIR = normpath(abspath(join(dirname(__file__), '..', '..')))
    TEMPLATE_DIRS = (
        join(BASE_DIR, 'templates'),
    )
    

    If your master.html is in your templates directory, that error should be fixed, too.

    The is 'basis' of the BASE_DIR is dirname(__file__), which returns the directory containing the current file, settings.py. Then, the result is joined with '..' twice, that is, we go two directories up, so now we are in the top 'site' directory. We call abspath to make sure that it's an absolute path and normpath to remove double slashes etc.