【问题标题】:Understanding template paths in Django了解 Django 中的模板路径
【发布时间】:2016-04-06 22:56:48
【问题描述】:

我有点难以理解 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 at /)

显然我误解了一些重要的东西,所以任何建议都将不胜感激。

编辑:根据请求,这里是完整的回溯:

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

【问题讨论】:

  • from . import views &lt;- why? 因为您的views.py 存在于urls.py 文件所在的目录上。
  • 您使用的是新式TEMPLATES 设置吗?如果你是,Django 将忽略TEMPLATE_DIRS。您应该在 TEMPLATES 内设置 DIRS 选项。

标签: python django


【解决方案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',
            ],
        },
    },
]

在这一行中,您可以为模板指定任何文件夹,默认为“模板”

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

您可以像这样在项目中构建路径:os.path.join(BASE_DIR, ...)

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

'thirdauth_app',

(尽管正如我的评论所表明的那样,我不确定为什么在(项目根目录)/thirdauth/urls.py 中不需要时,我必须在应用程序中显式导入视图,但我想这是一个单独的问题。)

如果看到您的代码,您正在使用视图 (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')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-21
    • 2018-11-16
    • 1970-01-01
    • 2018-04-16
    • 2018-02-04
    • 1970-01-01
    相关资源
    最近更新 更多