模板不存在

时间:2013-06-18 11:57:02

标签: django django-templates

我是Django的新手。我在我的项目中创建了一个名为templates的文件夹,并在其中创建了“base.html”,它工作正常。但是当我在模板欢迎中创建新文件夹然后“home.html”时,我在views.py文件中写了一些代码行

from django.shortcuts import render_to_response

def hello(request):
    return render_to_response('welcome/home.html')

和settings.py包含

# Django settings for Telecom project.

DEBUG = True
TEMPLATE_DEBUG = DEBUG

import os
#BASE_DIR = os.path.dirname(os.path.dirname(__file__))

PROJECT_DIR = os.path.dirname(__file__)

ADMINS = (
    # ('Your Name', 'your_email@example.com'),
)


MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'mysql',                      # Or path to database file if using sqlite3.
        'USER': 'root',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '127.0.0.1',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '3306',                      # Set to empty string for default. Not used with sqlite3.
    }
}

# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/{{ docs_version }}/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'UTC'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')


# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = 'http://localhost:8000/media/admin/'

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = 'b9_hyqe*b&ra_&wlm5a9xas_ag#5mjv-dy=to%hdk_u-#xvn*l'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#    'django.template.loaders.eggs.Loader',
)

TEMPLATE_DIRS = (       
                  os.path.join(PROJECT_DIR, 'templates'),

)

print PROJECT_DIR
MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

ROOT_URLCONF = 'Telecom.urls'

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    'django.contrib.admindocs',
    'welcome',
)

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

但错误显示

TemplateDoesNotExist at /hello/
/welcome/home.html
Request Method: GET
Request URL:    http://localhost:8000/hello/
Django Version: 1.6
Exception Type: TemplateDoesNotExist
Exception Value:    
/welcome/home.html
Exception Location: C:\Python27\django\template\loader.py in find_template, line 131
Python Executable:  C:\Python27\python.exe
Python Version: 2.7.2
Python Path:    
['D:\\Bishnu\\BE\\4th year\\8th semester\\Major Project II\\Working\\Workspace\\Telecom',
 'C:\\Python27\\lib\\site-packages\\distribute-0.6.35-py2.7.egg',
 'D:\\Bishnu\\BE\\4th year\\8th semester\\Major Project II\\Working\\Workspace\\Telecom',
 'C:\\Python27\\DLLs',
 'C:\\Python27\\lib',
 'C:\\Python27\\lib\\plat-win',
 'C:\\Python27\\lib\\lib-tk',
 'C:\\Python27',
 'C:\\Python27\\lib\\site-packages',
 'C:\\Python27\\lib\\site-packages\\wx-2.8-msw-unicode',
 'C:\\Windows\\SYSTEM32\\python27.zip']
Server time:    Tue, 18 Jun 2013 17:09:07 +0545

我该如何解决?

15 个答案:

答案 0 :(得分:16)

对于Django 1.8或更高版本 您必须在DIRS列表的TEMPLATES键中添加模板路径作为字符串列表。

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['Secondjango/Secondjango/templates/welcome'],        #<<<<<<<<Here
        '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 :(得分:14)

由于模板目录不正确,可能会出现此错误 尝试对settings.py进行一些更改,如下所示

import os.path
Temp_Path = os.path.realpath('.')
...
STATIC_ROOT = ''    
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'
...
TEMPLATE_DIRS = (
    Temp_Path +"/template"
)

然后将所有模板放在模板文件夹和css / javascript文件中的静态文件夹中,该文件夹位于应用程序文件夹中。希望这能解决你的问题。

My suggestion don't put template folder inside application folder

  

Django会选择找到名字匹配的第一个模板,和   如果在不同的应用程序中有一个具有相同名称的模板,   Django无法区分它们。我们需要能够   将Django指向正确的位置,这是确保这一点的最简单方法   是通过命名它们。也就是说,将这些模板放在里面   另一个为应用程序本身命名的目录。

答案 2 :(得分:4)

试试这个:

在您的settings.py文件中替换

 
TEMPLATE_DIRS = (       
                  os.path.join(PROJECT_DIR, 'templates'),

)
 

 
TEMPLATE_DIRS = (       
                  os.path.join(PROJECT_DIR, 'templates'),
                  os.path.join(PROJECT_DIR, 'templates/welcome')

)
 

然后,在您的代码中,只需调用 render_to_response(“home.html”)

这应该可以解决您的问题。

答案 3 :(得分:2)

您可以使用: 在settigns.py

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


STATICFILES_DIRS = (
    'static',
)

答案 4 :(得分:2)

对于Django 1.8或更高版本,只需在设置文件的TEMPLATES DIR变量列表中添加以下内容

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': ['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',
        ],
    },
},
]

此属性指向模板目录'DIRS': ['templates'],

答案 5 :(得分:2)

对于Django 2.0,我将设置文件中TEMPLATES的值DIRS编辑到项目的入口目录:

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': ['.'], # here set DIRS to project's entry directory
    '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',
        ],
    },
},

并且Mac和Windows系统都解决了这个问题。

答案 6 :(得分:1)

假设你有一个django项目“my_project”,以及应用程序“app_1”和“app_2”

my_project
    -- my_project  
    -- manage.py
    welcome
        -- __init__.py
        templates               
            -- home.html
        -- models.py
        -- views.py

    app_1
        -- __init__.py
        templates
            welcome
                -- home.html
        -- models.py
        -- views.py
    app_2
        templates
            a_subfolder
               -- home.html
        -- __init__.py
        -- models.py
        -- views.py

现在,如果您有一些设置,例如。

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

)
#...

INSTALLED_APPS = (
    'app_2', 
    'app_1',
    'welcome',
    #...
)

#...

django会这样做: 当您致电render_to_response('welcome/home.html')时(我认为某些参数缺失),django会在所有应用程序中的某个“欢迎”文件夹中查看“home.html”文件(在本例中为“app_1”和“app_2”)有一个“模板”文件夹。 (这是一种惯例)

修改

我已经添加了“欢迎”应用。

您必须在没有应用名称render_to_response('home.html')

的情况下调用该方法

答案 7 :(得分:1)

检查&#34; hello.html&#34;中是否有任何包含标签已经给出了不存在的文件路径。提出的错误也是如此: -

/ hello /上的TemplateDoesNotExist /welcome/home.html

答案 8 :(得分:1)

请检查您是否已将新应用程序添加到INSTALLED_APPS下的settings.py文件中

Django编译了所有的模板&#39;项目中所有应用程序的文件夹都放在一个单独的模板中。夹。

请记住在您的应用程序中创建单独的目录&#39;模板&#39;文件夹,使Django框架更容易找到您正在寻找的模板。

答案 9 :(得分:0)

通过scores_matrix['Dog'][1] >>> 2 scores_matrix['Cat'][2] >>> 0

将模板目录添加到项目settings.py中的 TEMPLATES

所以最终的模板应该类似于以下内容

'DIRS': [os.path.join(BASE_DIR, 'templates')],

答案 10 :(得分:0)

这样做

->确保模板文件夹应位于根文件夹中,而不应位于应用程序文件夹中 ->然后转到您的setting.py文件,然后寻找TEMPLATES = [ 'DIRS': ] ->在DIRS中,将模板文件夹的路径设置为'DIRS':[r'path']

它将起作用

答案 11 :(得分:0)

另一个原因可能是您应用中的文件夹名称是template而不是templates。最后请注意

答案 12 :(得分:0)

您的settings.py文件必须为:

'DIRS':[“模板”]

您的模板文件夹必须在您的主项目名称下:

Like that

答案 13 :(得分:0)

我所要做的就是将“rest_framework”安装为应用程序之一。

答案 14 :(得分:-3)

您是否在__init__.py文件夹中创建了文件welcome