python - django 错误 TemplateDoesNotExist

标签 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>

我的网站/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'),
)

最佳答案

您的问题出在您的设置上。您目前拥有:

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

感谢您如此详尽地回答您的问题。祝你好运!

关于python - django 错误 TemplateDoesNotExist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30891707/

相关文章:

python - 如何获取随机数值并将其附加到文件名

python - 多次拟合回归并收集汇总统计数据

python - __init__.py 的目的。或者 : Why put code in __init__. py 而不是模块?

html - 当我需要从 WYSIWYG 编辑器呈现 HTML 时如何防止 XSS 攻击?

python - Django 中的重定向

Python:字典列表,如何获取列表中多个项目的特定键的值?

python - 导入文件时在 Django 中使用事务

python - 从 django 模板解析 session

django - 自定义模板标签 args 和 kwargs 解析器

django 1.5 如何从内存中读取 csv