[Django]-Using absolute paths in django templates

1πŸ‘

βœ…

All of your html templates should live under the templates directory (including your base.html). The location of this folder is set using the TEMPLATE_DIRECTORY settings in your settings.py. The static folder is solely for css, js, etc.

When inheriting from another template using the extends tag, the path you give is always relative to your template directory, not project.

2πŸ‘

Your base.html should be residing in a templates directory and not in the static directory.

This is because you define where django searches for templates using the TEMPLATE_DIRS in your settings.py file. Here, I give an example which computes your TEMPLATE_DIRS value dynamically.

import os

TEMPLATE_DIRS = (
    os.path.join(os.path.dirname(__file__), '..', 'templates'),
)

In additional, you need to be aware that django depends on another setting called TEMPLATE_LOADERS to determine the priority in which it loads up your html files/templates, while searching through your templates directories.

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

Once your base.html is located in your templates directory, all you need to do in your html files is to write:-

{% extends "base.html" %}

and you would extend correctly

πŸ‘€Calvin Cheng

Leave a comment