模板不存在 [英] Template does not exist

查看:138
本文介绍了模板不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是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')

and settings.py包含

 #Django设置为电信项目。 

DEBUG = True
TEMPLATE_DEBUG = DEBUG

import os
#BASE_DIR = os.path.dirname(os.path.dirname(__ file__))

PROJECT_DIR = os.path.dirname(__ file__)

ADMINS =(
#('您的姓名','your_email@example.com'),



经理= ADMINS

DATABASES = {
'默认':{
'ENGINE':'django。 db.backends.mysql',#添加'postgresql_psycopg2','postgresql','mysql','sqlite3'或'oracle'。
'NAME':'mysql',#或使用sqlite3的数据库文件路径。
'USER':'root',#不与sqlite3一起使用。
'PASSWORD':'',#不与sqlite3一起使用。
'HOST':'127.0.0.1',#设置为localhost的空字符串。不适用于sqlite3。
'PORT':'3306',#设置为空字符串为默认值。不适用于sqlite3。
}
}

#对本网站有效的主机/域名;如果DEBUG为False,则需要
#请参阅https://docs.djangoproject.com/en/ {{docs_version}} / ref / settings /#allowed-hosts
ALLOWED_HOSTS = []

#此安装的本地时区。可以在这里找到选择:
#http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
#虽然并不是所有的操作系​​统都可以选择所有选项。
#在Unix系统上,值为None将导致Django与操作系统使用相同的
#timezone。
#如果在Windows环境中运行,必须设置为与
#系统时区相同。
TIME_ZONE ='美国/芝加哥'

#此安装的语言代码。所有选择都可以在这里找到:
#http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE ='UTC'

SITE_ID = 1

#如果将其设置为False,Django将进行一些优化,以便
#加载国际化机制。
USE_I18N = True

#如果将其设置为False,Django将不会根据当前的区域设置格式化日期,数字和
#日历
USE_L10N = True

#将保存用户上传文件的目录的绝对文件系统路径。
#示例:/home/media/media.lawrence.com/media/
MEDIA_ROOT = os.path.join(PROJECT_DIR,'media')


#URL处理从MEDIA_ROOT提供的媒体。确保使用
#尾部斜线。
#示例:http://media.lawrence.com/media/,http://example.com/media/
MEDIA_URL ='http:// localhost:8000 / media / admin /'

#目录静态文件的绝对路径应该收集到。
#不要把任何东西放在这个目录下;在应用程序的static /子目录和STATICFILES_DIRS中存储静态文件
#。
#示例:/home/media/media.lawrence.com/static/
STATIC_ROOT =''

#静态文件的URL前缀。
#示例:http://media.lawrence.com/static/
STATIC_URL ='/ static /'

#admin静态文件的URL前缀 - CSS ,JavaScript和图像。
#确保使用尾部斜线。
#示例:http://foo.com/static/admin/,/ static / admin /。
ADMIN_MEDIA_PREFIX ='/ static / admin /'

#静态文件的附加位置
STATICFILES_DIRS =(
#将字符串放在这里,如/ home / html /静态或C:/ www / django / static
#即使在Windows上也可以使用正斜杠
#不要忘记使用绝对路径,而不是相对路径


#知道如何在
#各个位置找到静态文件的finder类的列表。
STATICFILES_FINDERS =(
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#'django.contrib.staticfiles .finders.DefaultStorageFinder',


#使其独一无二,不要与任何人共享。
SECRET_KEY ='b9_hyqe * b& ra_& wlm5a9xas_ag#5mjv-dy = to%hdk_u-#xvn * l'

#知道如何从各种来源导入模板的可调用列表。
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'),



打印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',
'dja ngo.contrib.staticfiles',
#取消注释下一行以启用admin:
'django.contrib.admin',
#取消注释下一行以启用管理文档:
'django.contrib.admindocs',
'welcome',


#样本记录配置。通过此配置执行的唯一有形日志
#是发送电子邮件到
#每个HTTP 500错误的站点管理员。
#有关如何自定义日志配置的详细信息,请参阅http://docs.djangoproject.com/en/dev/topics/logging for
#。
LOGGING = {
'version':1,
'disable_existing_loggers':False,
'handlers':{
'mail_admins':{
'级别':'错误',
'class':'django.utils.log.AdminEmailHandler'
}
},
'loggers':{
'django .request':{
'handlers':['mail_admins'],
'level':'ERROR',
'propagate':True,
},
}
}

但错误显示

  TemplateDoesNotExist at / hello / 
/welcome/home.html
请求方法:GET
请求URL:http:// localhost: 8000 / hello /
Django版本:1.6
异常类型:TemplateDoesNotExist
异常值:
/welcome/home.html
异常位置:C:\Python27\\ \\ django\template\loader.py在find_template中,第131行
Python可执行文件:C:\\ Python27 \python.exe
Python版本:2.7.2
Python路径:
['D:\\Bishnu\\BE\\4th year\\\ \\第八学期\\Major Project II \\Working\\Workspace\\Telecom',
'C:\\Python27\\lib\\\\site- package \\distribute-0.6.35-py2.7.egg',
'D:\\Bishnu\\BE\\\\\,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, \\ 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-uni代码',
'C:\\Windows\\\SYSTEM32\\python27.zip']
服务器时间:星期二,2013年6月18日17:09:07 +0545

如何解决?

解决方案

由于模板目录不正确,可能会出现此错误
请尝试在 settings.py 中进行以下更改

  import os.path 
Temp_Path = os.path.realpath('。')
...
STATIC_ROOT =''
#静态文件的URL前缀。
#示例:http://example.com/static/,http://static.example.com/
STATIC_URL ='/ static /'
...
TEMPLATE_DIRS =(
Temp_Path +/ template

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



我的建议不要在应用程序文件夹中放置模板文件夹


Django将选择找到名称匹配的第一个模板,
如果您在不同的应用程序中使用了同名的模板,
Django将无法区分它们。我们需要能够
将Django指向正确的方法,而确保这个
的最简单的方法是通过命名来替代它们。也就是说,将这些模板放在
另一个为应用程序本身命名的目录。



I am new to Django. I made a folder named templates in my project and "base.html" inside it, it works fine. But when I make new folder inside templates welcome and then "home.html" and I write some lines of code in my views.py file as

from django.shortcuts import render_to_response

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

and settings.py includes

# 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,
        },
    }
}

but the error shows

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

How can I solve it ?

解决方案

This error may arises due to the incorrect template directories Try some change on settings.py as below

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"
)

Then put all your template inside template folder and css/javascript file in static folder which is located inside your application folder. Hope this will solve your problem.

My suggestion don't put template folder inside application folder

Django will choose the first template it finds whose name matches, and if you had a template with the same name in a different application, Django would be unable to distinguish between them. We need to be able to point Django at the right one, and the easiest way to ensure this is by namespacing them. That is, by putting those templates inside another directory named for the application itself.

这篇关于模板不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆