Skip to main content
 首页 » 编程设计

python之了解 Django 中的模板路径

2025年05月04日34artech

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

(虽然正如我的评论所表明的,我不确定为什么我必须在应用程序中显式导入 View ,而这在(项目根目录)/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 

请您参考如下方法:

像这样更改您的设置文件:

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

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

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

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

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

'thirdauth_app', 

(Though as my comment indicates, I'm not exactly sure why I have to import views explicitly in an app when this isn't necessary in (project root)/thirdauth/urls.py, but I suppose that's a separate question.)

如果看到你的代码,你正在使用一个 View (views.home)

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

因此您需要将您的 View 导入urls.py

然后在你的 views.py 中:

from django.shortcuts import render 
 
def home(request): 
    return render(request,'thirdauth_app/home.html')