Django错误:模板不存在

10

我是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),
]

main/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个回答

16

你的问题在于你的设置。你当前拥有:

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
您可能忘记在settings.py文件的INSTALLED_APPS中包含应用程序的名称。我认为这可能会对某些人有所帮助。

不,他没有忘记那个。 - pptaszni

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

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

并且

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

如果你想要访问位于<project>/templates内的模板,那么你需要在TEMPLATES中指定DIRS
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',
            ],
        },
    },
]

它是设置 - 在Django 1.8模板dirs已经移动到TEMPLATES []内部。 - FlipperPA

1

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", {})


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

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

]


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

0
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文件,同时也需要导入views

将你的代码更改为以下内容

urls.py #在mysite/文件夹中

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
]

你需要在你的应用程序主目录下创建一个名为urls.py的新文件 #在main/文件夹中

from django.urls.conf import path
from . import views

app_name = 'main'

urlpatterns = [
    path('', views.hello, name="hello"),
]

在主文件夹中创建的最后一个文件,告诉你的项目在主应用程序上有哪些URL。


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