在 /base.html 上,模板不存在。

18

朋友们, 我尝试按照书籍《学习Django Web开发》(作者:Sanjeev Jaiswal)中的项目示例进行重复操作。

运行服务器后,我遇到了以下异常信息:TemplateDoesNotExist at /base.html

TemplateDoesNotExist at /
base.html

Request Method:     GET
Request URL:    http://127.0.0.1:8000/
Django Version:     1.8.3
Exception Type:     TemplateDoesNotExist
Exception Value:    base.html

Exception Location: C:\Python34\lib\site-packages\django\template\loader.py in get_template, line 46
Python Executable:  C:\Python34\python.EXE
Python Version:     3.4.3
Python Path:    

['C:\\dj\\mytweets',
'C:\\WINDOWS\\system32\\python34.zip',
'C:\\Python34\\DLLs',
'C:\\Python34\\lib',
'C:\\Python34',
'C:\\Python34\\lib\\site-packages']

Server time:    Tue, 14 Jul 2015 14:01:27 +0300

模板加载器排错

Django tried loading these templates, in this order:

    Using loader django.template.loaders.filesystem.Loader:
    Using loader django.template.loaders.app_directories.Loader:
        C:\Python34\lib\site-packages\django\contrib\admin\templates\base.html (File does not exist)
        C:\Python34\lib\site-packages\django\contrib\auth\templates\base.html (File does not exist)

我的settings.py文件:

import os

SETTINGS_PATH = os.path.dirname(__file__)
PROJECT_PATH = os.path.join(SETTINGS_PATH, os.pardir)
PROJECT_PATH = os.path.abspath(PROJECT_PATH)
TEMPLATE_PATH = os.path.join(PROJECT_PATH, "templates")

SECRET_KEY = 'khcr3h6u+ghi+rtb+g_(mvgq!mtn9u4&%=hu20vt2*u(p8-kde'

DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'tweets',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'mytweets.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(PROJECT_PATH, 'templates')],
        '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',
            ],
        },
    },
]

WSGI_APPLICATION = 'mytweets.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(PROJECT_PATH, 'db.sqlite3'),
    }
}

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(
        os.path.dirname(__file__),
        'static',
    ),
)

TEMPLATE_DIRS = (
    TEMPLATE_PATH,
)

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

我也尝试了这样修改 settings.py 文件:

修改后的 settings.py 文件:

import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_PATH = os.path.join(BASE_DIR, "templates")

SECRET_KEY = 'khcr3h6u+ghi+rtb+g_(mvgq!mtn9u4&%=hu20vt2*u(p8-kde'

DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'tweets',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'mytweets.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        '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',
            ],
        },
    },
]

WSGI_APPLICATION = 'mytweets.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(
        os.path.dirname(__file__),
        'static',
    ),
)

我的项目结构:

我的项目结构:

views.py:

from django.views.generic import View
from django.shortcuts import render


class Index(View):
    def get(self, request):
        params = {}
        params['name'] = 'Django'
        return render(request, 'base.html', params)

urls.py:

from django.conf.urls import patterns, include, url
from django.contrib import admin
from tweets.views import Index
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^$', Index.as_view()),
    url(r'^admin/', include(admin.site.urls)),
)

追踪:

Template Loader Error:
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
Using loader django.template.loaders.app_directories.Loader:
C:\Python34\lib\site-packages\django\contrib\admin\templates\base.html    (File does not exist)
C:\Python34\lib\site-packages\django\contrib\auth\templates\base.html (File does not exist)



Traceback:
File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response  
132.response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python34\lib\site-packages\django\views\generic\base.py" in view  
71.return self.dispatch(request, *args, **kwargs)
File "C:\Python34\lib\site-packages\django\views\generic\base.py" in dispatch  
89.return handler(request, *args, **kwargs)
File "C:\dj\mytweets\tweets\views.py" in get  
9.return render(request, 'base.html', params)
File "C:\Python34\lib\site-packages\django\shortcuts.py" in render
67.template_name, context, request=request, using=using)
File "C:\Python34\lib\site-packages\django\template\loader.py" in render_to_string 
98.template = get_template(template_name, using=using)
File "C:\Python34\lib\site-packages\django\template\loader.py" in get_template  
46.raise TemplateDoesNotExist(template_name)

Exception Type: TemplateDoesNotExist at /
Exception Value: base.html

请问应该改变什么来让页面渲染出来?


请问你能否分享一下mytweets/urls.py和tweets/views.py这两个文件。 - Christoffer Karlsson
好的,没问题。请稍等一下。 - ufo
5个回答

20

我不熟悉你所使用的书籍,因此无法基于那本书籍给你任何建议。如果这本书是针对Django 1.7的,当你开始学习Django时,使用Django 1.7会更容易些。

如果你想继续使用Django 1.8,在这里告诉你如何解决你目前遇到的错误:

你的settings.py文件中有一些旧的模板配置项,例如TEMPLATE_DIRSTEMPLATE_LOADERS(适用于Django <= 1.7),以及新的配置项在TEMPLATES下(适用于Django 1.8 +)。

首先,删除旧的TEMPLATE_DIRSTEMPLATE_LOADERS配置项。

其次,看起来TEMPLATES设置中的DIRS不正确。

定义BASE_DIR,它应该在你运行./ manage.py startproject时默认包含在settings.py中。

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

然后将TEMPLATES更改为

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        ...

嗨,谢谢你的提示。我按照你的建议更改了所有设置,但是没有帮助。 - ufo
当您将print(TEMPLATES)添加到您的settings.py时,它会显示什么?请[编辑]您的问题并包含新的traceback。复制并粘贴文本而不是包含屏幕截图。 - Alasdair
print(TEMPLATES) 显示以下列表:[{'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']}, 'APP_DIRS': True, 'DIRS': ['C:\Documents and Settings\Admin\Мои документы\dj\mytweets\templates'], 'BACKEND': 'django.template.backends.django.DjangoTemplates'}] - ufo
现在您已更改设置,回溯信息怎么样了? - Alasdair
我正在使用Django 4.0.5,在settings.py的TEMPLATES中添加'DIRS': [BASE_DIR / 'templates'],,如果你的项目中的模板文件夹名为templates。 - AnonymousUser
显示剩余5条评论

2

我曾经遇到过同样的问题,一开始我尝试通过将HTML模板中的路径从{% extends "base.html" %}更改为{% extends "foldername/template/base.html" %}来解决它,但是没有成功。

之后,我在每个项目的模板文件夹中的'base.html'文件中添加了一些内容。这对我有用。


0
我曾经遇到过这个问题,即我的项目中找不到base.html模板。我通过将templates目录移动到调用该模板的应用程序之后来解决了这个问题(在出现问题之前)。
--my_project
 --templates
 --app_a
(after fixed)
--my_project
 --app_a
 --templates

0

在已安装的应用中,将“tweets”替换为“mytweets”。


-4

在 settings.py 的 DIR [] 中设置您的模板路径

 TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [**'C:\\Python27\\Lib\\site-packages\\django\\contrib\\admin\\templates\\admin'**],
        'APP_DIRS':True,
        'OPTIONS': {

永远不要在设置中使用硬编码路径——上面的代码有两个主要问题——它不仅是硬编码的 + 很多人甚至没有 C 盘,更不用说部署到生产环境中根本行不通——但无论如何,硬编码路径都违反了适当的软件工程和编码约定... - Radek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接