了解Django中的模板路径

时间:2016-01-03 00:58:12

标签: python django

我在理解Django查找模板文件的方式时遇到了一些困难。

我正在关注一个教程,在(项目目录)/thirdauth/settings.py中,我有以下内容:

# See: http://stackoverflow.com/questions/15411164/django-templates-folders
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
TEMPLATE_DIRS = [
    os.path.join(PROJECT_ROOT, 'thirdauth_app/templates'),
]

在(项目根目录)/thirdauth/urls.py中,我有以下内容:

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

然后在(项目根目录)/thirdauth_app/urls.py我有这个:

from . import views  # <- why?

urlpatterns = [
    url(r'^$', views.home, name='home')
]

(虽然正如我的评论所示,我不确定为什么我必须在(项目根目录)/thirdauth/urls.py中没有必要时在应用程序中显式导入视图,但我认为这是一个单独的问题。)

在(project_root)/thirdauth_app/views.py中如下:

def home(request):
    context = RequestContext(request, {'user': request.user})
    return render_to_response('thirdauth_app/home.html', context_instance=context)

最后,模板文件本身位于(项目根目录)/thirdauth_app/templates/thirdauth_app/home.html

不幸的是,在运行服务器时,我仍然收到TemplateDoesNotExist错误(在/的TemplateDoesNotExist)

显然我误解了一些至关重要的东西,所以任何建议都会受到极大的赞赏。

编辑:每个请求,这里是完整的追溯:

Environment:


Request Method: GET
Request URL: http://localhost:8000/

Django Version: 1.9.1
Python Version: 2.7.6
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'thirdauth']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 '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']

Template loader postmortem
Django tried loading these templates, in this order:

Using engine :
    * django.template.loaders.app_directories.Loader: /home/dbc/venv_projects/thirdauth/local/lib/python2.7/site-packages/django/contrib/admin/templates/home.html (Source does not exist)
    * django.template.loaders.app_directories.Loader: /home/dbc/venv_projects/thirdauth/local/lib/python2.7/site-packages/django/contrib/auth/templates/home.html (Source does not exist)



Traceback:

File "/home/dbc/venv_projects/thirdauth/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  149.                     response = self.process_exception_by_middleware(e, request)

File "/home/dbc/venv_projects/thirdauth/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  147.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/dbc/venv_projects/thirdauth/thirdauth/thirdauth_app/views.py" in home
  7.     return render_to_response('home.html', context_instance=context)

File "/home/dbc/venv_projects/thirdauth/local/lib/python2.7/site-packages/django/shortcuts.py" in render_to_response
  45.             using=using)

File "/home/dbc/venv_projects/thirdauth/local/lib/python2.7/site-packages/django/template/loader.py" in render_to_string
  137.             raise TemplateDoesNotExist(template_name, chain=chain)

Exception Type: TemplateDoesNotExist at /
Exception Value: home.html

1 个答案:

答案 0 :(得分:1)

更改您的设置文件:

<强> settings.py

import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
#...
#...
#...
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.core.context_processors.static',
            ],
        },
    },
]

在此行中,您可以指定模板的任何文件夹,它的模板&#39;默认情况下

'DIRS': [os.path.join(BASE_DIR,'<<<folder name>>>')],

您可以在项目中构建路径,如下所示:os.path.join(BASE_DIR, ...)

还要确保将您的应用定义为项目,在settings.py的INSTALLED_APPS部分末尾添加此代码:

'thirdauth_app',
  

(虽然正如我的评论所示,我不确定为什么我必须在(项目根目录)/thirdauth/urls.py中不必在app中显式导入视图,但我假设这是一个单独的问题。)

如果看到您的代码,则表示您正在使用视图(views.home

url(r'^$', views.home, name='home')

所以您需要将您的观点导入urls.py

然后在你的views.py中:

from django.shortcuts import render

def home(request):
    return render(request,'thirdauth_app/home.html')