django错误TemplateDoesNotExist

时间:2015-06-17 12:31:15

标签: python django django-templates

我是Django的新手,只是关注Django官方文档,但这是一个问题。

我使用

创建一个新的Django项目

Django 1.8.2 + PyCharm 4.5.1 + Python 3.4.3 + Windows 8.1

  - mysite
     - main
        - migrations
            __init__.py
        __init__.py
        admin.py
        models.py
        tests.py
        views.py
     - mysite
        __init__.py
        settings.py
        urls.py
        wsgi.py
     - templates
        hello.html
     db.sqlite3
     manage.py

其中大部分是自动创建的,我修改的内容如下:

模板/ hello.html的

<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="UTF-8">
  <title>Django test</title>
</head>
<body>
hello world!
</body>
</html>

的mysite / urls.py

from django.conf.urls import include, url
from django.contrib import admin
from main.views import hello

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^hello/$', hello),
]

主/ views.py

from django.shortcuts import render_to_response

def hello(request):
    return render_to_response('hello.html', locals())

并单击运行并访问localhost:8080,结果如下:

TemplateDoesNotExist at /hello/
hello.html
Request Method: GET
Request URL:    http://127.0.0.1:8000/hello/
Django Version: 1.8.2
Exception Type: TemplateDoesNotExist
Exception Value:    
hello.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:\\Users\\kant\\Desktop\\code\\PycharmProjects\\mysite',
 'C:\\Users\\kant\\Desktop\\code\\PycharmProjects\\mysite',
 'C:\\Windows\\SYSTEM32\\python34.zip',
 'C:\\Python34\\DLLs',
 'C:\\Python34\\lib',
 'C:\\Python34',
 'C:\\Python34\\lib\\site-packages']

如果我将views.py更改为

from django.http import HttpResponse

def hello(request):
    return HttpResponse("hello world")

它正确运行。

我认为它可能是由模板路径引起的,这里是settings.py,自动生成而不做修改:

"""
Django settings for mysite project.

Generated by 'django-admin startproject' using Django 1.8.2.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

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


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'p(fs&6e2kg6d3%0txc+9o=(!*8fzt8w5l6neuqer*m9qictsl$'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

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

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 = 'mysite.urls'

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',
            ],
        },
    },
]

WSGI_APPLICATION = 'mysite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

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


# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

STATIC_URL = '/static/'

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

8 个答案:

答案 0 :(得分:14)

您的问题与您的设置有关。你现在有:

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

这是在Django 1.7.x及更低版本中设置模板目录的方法。在Django 1.8.x中,将您的TEMPLATES []更改为如下所示:

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',
            ],
        },
    },
]

感谢你对你的问题如此彻底。祝你好运!

答案 1 :(得分:1)

尝试将模板放在子目录中:

 <project>/<app>/templates/<app>/hello.html

return render_to_response('<app>/hello.html', locals())

如果您想访问<project>/templates内的模板,则必须在DIRS内指定TEMPLATES

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',
            ],
        },
    },
]

答案 2 :(得分:0)

可能您忘记在INSTALLED_APPS下的settings.py中包含应用程序的名称。这可能对我相信的人有所帮助。

答案 3 :(得分:0)

settings.py

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

views.py
返回render(request,“”,{})
例子:
返回render(request,“ pages / template / home.html”,{})

答案 4 :(得分:0)

在模板文件夹中更容易的解决方案是创建另一个文件夹,并将其命名为您的应用程序名称,这样您的文件树应如下所示:

 - mysite
 - main
    - migrations
        __init__.py
    __init__.py
    admin.py
    models.py
    tests.py
    views.py
 - mysite
    __init__.py
    settings.py
    urls.py
    wsgi.py
 - templates
   -mysite
       hello.html
 db.sqlite3
 manage.py

答案 5 :(得分:0)

我遇到了同样的错误,但不知道是什么原因造成的。我意识到我没有将我的应用程序添加到 Django 已安装应用程序列表中。以前是这样的:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

现在我添加了我的应用程序,它看起来像

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'main',
]

答案 6 :(得分:0)

试试这个方法,在你的 settings.py 中进行更改

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

]

答案 7 :(得分:0)

try {
    javax.xml.parsers.DocumentBuilderFactory dbf = 
             javax.xml.parsers.DocumentBuilderFactory.newInstance();
    javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
    org.w3c.dom.Document document = db.parse(new java.io.File("Students.xml"));
    org.w3c.dom.NodeList nodeList = document.getElementsByTagName("student");
    for(int x = 0,size = nodeList.getLength(); x < size; x++) {
        System.out.println(nodeList.item(x).getAttributes()
                           .getNamedItem("id").getNodeValue()); // HERE :)
    }
}
catch (org.xml.sax.SAXException | java.io.IOException | javax.xml.parsers.ParserConfigurationException ex) {
    ex.printStackTrace();
}

你必须导入你的应用主目录的 urls.py 你正在导入视图

像这样改变你的代码

urls.py #in 文件夹 mysite/

mysite/urls.py

from django.conf.urls import include, url
from django.contrib import admin
from main.views import hello # this is the error

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^hello/$', hello), # bad bad bad
]

你必须在你的应用主目录中创建一个新文件 命名 urls.py #in 文件夹 main/

from django.conf.urls import path, include, url
from django.contrib import admin
from . import views ##add this line

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url('main/', include(main.urls), name='main'), ## add this line
]

您在主文件夹中创建的最后一个文件 告诉你的项目在主应用上有网址