23

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

我该如何解决?

4

15 回答 15

24

对于 Django 1.8 或更高版本,您需要打开settings.py文件并将模板路径添加到 list 的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',
            ],
        },
    },
]

谢谢。

于 2016-04-16T20:50:09.570 回答
20

由于模板目录不正确,可能会出现此错误尝试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 文件放在位于应用程序文件夹内的静态文件夹中。希望这能解决您的问题。

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

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

于 2013-07-30T08:50:15.517 回答
6

尝试这个:

在您的 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")

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

于 2013-06-18T15:36:50.207 回答
3

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

于 2017-01-28T21:26:05.493 回答
3

对于 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 系统上都解决了这个问题。

于 2017-12-22T17:28:24.350 回答
2

您可以使用:在 settigns.py

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


STATICFILES_DIRS = (
    'static',
)
于 2015-03-12T22:13:04.237 回答
2

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

Django 将项目中所有应用程序中的所有“模板”文件夹编译到一个“模板”文件夹中。

请记住在您的应用程序“模板”文件夹中创建单独的目录,以便 Django 框架更容易找到您正在寻找的模板。

于 2018-02-22T21:16:11.680 回答
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')

于 2013-06-18T12:38:02.413 回答
1

检查“hello.html”中是否有任何包含标签,其文件路径不存在。提出的错误是一样的:-

TemplateDoesNotExist 在 /hello/ /welcome/home.html

于 2016-04-25T04:42:17.893 回答
0

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

于 2021-06-17T00:01:33.777 回答
0

做这个

-> 确保你的模板文件夹应该在根文件夹而不是 app 文件夹中 -> 然后转到你的 setting.py 文件并查找TEMPLATES = [ 'DIRS': ] -> 在 DIRS 中输入你的模板文件夹的路径,如下所示'DIRS':[r'path']

它会起作用的

于 2018-12-06T11:54:26.023 回答
0

另一个原因可能是您的应用程序中的文件夹名称是否templatetemplates. 注意最后的's'

于 2019-02-21T05:21:24.027 回答
0

通过将模板目录添加到 项目中的TEMPLATESsettings.py'DIRS': [os.path.join(BASE_DIR, 'templates')],

所以最终的 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',
            ],
        },
    },
]
于 2018-07-11T07:57:32.913 回答
0

您的 settings.py 文件必须是:

'DIRS':[“模板”]

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

像那样

于 2019-03-14T18:25:07.007 回答
-3

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

于 2013-06-18T13:36:51.567 回答