Django扩展了全局模板

时间:2017-09-10 07:11:18

标签: django django-templates django-views

我是Django的新手并在Django 1.11

中创建了第一个应用程序

我创建了三个应用pagesuserssearch,目录结构为

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

myapp/pages/views.py包含

from django.views.generic import TemplateView


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

myapp/pages/templates/pages/home.html包含

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

myapp/templates/base.html包含

{% 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>

但是当我尝试访问时

http://127.0.0.1:8000/pages

它给出错误

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)

如何在视野中加载base.html

由于所有三个应用都将使用常见的导航和静态文件,因此我不想单独包含在应用中。

  

编辑2&gt;的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',
            ],
        },
    },
]

1 个答案:

答案 0 :(得分:1)

您必须在TEMPLATES设置(在settings.py文件中)中添加项目文件夹中的templates目录:

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