Anuj TBE
Anuj TBE

Reputation: 9826

Django extend global template

I'm new to Django and creating first application in Django 1.11

I have created three application pages, users, search and directory structure is as

myapp
|- pages
   |- templates
      |- pages
         |- home.html
   |- urls.py
   |- views.py
   |- ...
|- search
   |- templates
      |- search
         |- index.html
|- myapp
   |- settings.py
   |- urls.py
|- static
   |- css
      |- style.css
   |- js
      |- script.js
|- templates
   |- base.html
|- manage.py

In the myapp/pages/views.py contain

from django.views.generic import TemplateView


class HomeView(TemplateView):
    template_name = 'pages/home.html'

myapp/pages/templates/pages/home.html contains

{% extends 'base.html' %}
{% block content %}
   <h1>Home page</h1>
{% endblock %}

myapp/templates/base.html contains

{% load static %}
<html>
  <head>
    <link href="{% static 'css/style.css' %}">
    ...
  </head>
  <body>
    <header>
       Welcome to my app
    </header>
    <div class="container">
       {% block content %}
       {% endblock %}
    </div>
  </body>
</html>

But when I try to access

http://127.0.0.1:8000/pages

it gives error as

Exception Type:     TemplateDoesNotExist
Exception Value: base.html


Template-loader postmortem

Django tried loading these templates, in this order:

Using engine django:

    django.template.loaders.app_directories.Loader: /path_to_app/seotool/pages/templates/base.html (Source does not exist)
    django.template.loaders.app_directories.Loader: /usr/local/lib/python3.6/site-packages/django/contrib/admin/templates/base.html (Source does not exist)
    django.template.loaders.app_directories.Loader: /usr/local/lib/python3.6/site-packages/django/contrib/auth/templates/base.html (Source does not exist)

How to load base.html in view.

Since all three apps will be using common navigation and static files, I don't want to included separately in apps.

Edit 2 > myapp/myapp/settings.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Upvotes: 0

Views: 720

Answers (1)

doru
doru

Reputation: 9110

You have to add the templates directory from your project folder in the TEMPLATES setting (in your settings.py file):

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [os.path.join(BASE_DIR, 'templates')],
    'APP_DIRS': True,
    'OPTIONS': {
        # ... some options here ...
    },
},

]

Upvotes: 1

Related Questions