存在模板时的 Django 3.1 TemplateNotFound 异常

Posted

技术标签:

【中文标题】存在模板时的 Django 3.1 TemplateNotFound 异常【英文标题】:Django 3.1 TemplateNotFound Exception when Template is Present 【发布时间】:2020-12-31 03:51:39 【问题描述】:

我正在努力部署我的应用程序并在 Windows 上完成了我的大部分工作。但是,现在我已将其移至 AWS,它不再工作了。

在任何人链接其他文章之前,这里是我尝试过的所有事情的列表:

os.path.join(BASE_DIR,'templates') 添加到TEMPLATE_DIR 更改我的模板的权限 我的应用在我的 INSTALLED_APPS 变量中 我检查了我所有的render 方法的格式是否正确 完全重新下载了我的项目

就像我之前说的,它可以在我的 Windows 机器上运行,但不能在 AWS 或我的 Mac 上运行。更奇怪的是错误说

Django tried loading these templates, in this order:

Using engine django:
    * django.template.loaders.filesystem.Loader: /opt/bitnami/apps/django/django_projects/goFiles/uploads/templates/uploads/base.html  (Source does not exist)
    * django.template.loaders.app_directories.Loader: /opt/bitnami/apps/django/django_projects/goFiles/uploads/templates/uploads/base.html  (Source does not exist)
    * django.template.loaders.app_directories.Loader: /opt/bitnami/python/lib/python3.8/site-packages/django/contrib/admin/templates/uploads/base.html  (Source does not exist)
    * django.template.loaders.app_directories.Loader: /opt/bitnami/python/lib/python3.8/site-packages/django/contrib/auth/templates/uploads/base.html  (Source does not exist)

/opt/bitnami/apps/django/django_projects/goFiles/uploads/templates/uploads/base.html 是我正在寻找的模板的正确绝对路径。如果我尝试使用该绝对路径cat 那个文件,它会打印到stdout。话虽如此,我将包含我的一些代码以供严格审查。

views.py

def get(self, request, *args, **kwargs):
        paste = None
        return render(request, 'uploads/index.html', 'paste': paste)

    def post(self, request, *args, **kwargs):
        paste = request.POST
        if is_post_valid(request):
            return upload(request)
        return render(request, 'uploads/index.html', 'paste': paste)

INSTALLED_APPS

INSTALLED_APPS = [
    'uploads.apps.UploadsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

模板

TEMPLATES = [
    
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['/opt/bitnami/apps/django/django_projects/goFiles/uploads/templates/uploads/'],
        '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',
            ],
        ,
    ,
]

全栈跟踪

Environment:


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

Django Version: 3.1
Python Version: 3.8.5
Installed Applications:
['uploads.apps.UploadsConfig',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
['goFiles.middleware.upload.UploadCheckMiddleware',
 'django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

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

Using engine django:
    * django.template.loaders.filesystem.Loader: /opt/bitnami/apps/django/django_projects/goFiles/uploads/templates/uploads/base.html  (Source does not exist)
    * django.template.loaders.app_directories.Loader: /opt/bitnami/apps/django/django_projects/goFiles/uploads/templates/uploads/base.html  (Source does not exist)
    * django.template.loaders.app_directories.Loader: /opt/bitnami/python/lib/python3.8/site-packages/django/contrib/admin/templates/uploads/base.html  (Source does not exist)
    * django.template.loaders.app_directories.Loader: /opt/bitnami/python/lib/python3.8/site-packages/django/contrib/auth/templates/uploads/base.html  (Source does not exist)


Template error:
In template /opt/bitnami/apps/django/django_projects/goFiles/uploads/templates/uploads/index.html, error at line 1
   uploads/base.html 
   1 :  % extends "uploads/base.html "% 
   2 : % load static %
   3 : % block content %
   4 :     <div class="w3-container w3-border w3-border-color-gray" id="paste_container">
   5 :       <!-- Source: https://codepen.io/jacoahmad/pen/vZXrOm -->
   6 :       <div class="o-constrained" id="o-constrained">
   7 :         % if messages %
   8 :         % for message in messages %
   9 :           <div class="w3-panel w3-red w3-round">
   10 :             <p>message<p>
   11 :           </div>


Traceback (most recent call last):
  File "/opt/bitnami/python/lib/python3.8/site-packages/django/template/backends/django.py", line 61, in render
    return self.template.render(context)
  File "/opt/bitnami/python/lib/python3.8/site-packages/django/template/base.py", line 170, in render
    return self._render(context)
  File "/opt/bitnami/python/lib/python3.8/site-packages/django/template/base.py", line 162, in _render
    return self.nodelist.render(context)
  File "/opt/bitnami/python/lib/python3.8/site-packages/django/template/base.py", line 938, in render
    bit = node.render_annotated(context)
  File "/opt/bitnami/python/lib/python3.8/site-packages/django/template/base.py", line 905, in render_annotated
    return self.render(context)
  File "/opt/bitnami/python/lib/python3.8/site-packages/django/template/loader_tags.py", line 127, in render
    compiled_parent = self.get_parent(context)
  File "/opt/bitnami/python/lib/python3.8/site-packages/django/template/loader_tags.py", line 124, in get_parent
    return self.find_template(parent, context)
  File "/opt/bitnami/python/lib/python3.8/site-packages/django/template/loader_tags.py", line 103, in find_template
    template, origin = context.template.engine.find_template(
  File "/opt/bitnami/python/lib/python3.8/site-packages/django/template/engine.py", line 129, in find_template
    raise TemplateDoesNotExist(name, tried=tried)

The above exception (uploads/base.html ) was the direct cause of the following exception:
  File "/opt/bitnami/python/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/opt/bitnami/python/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/opt/bitnami/python/lib/python3.8/site-packages/django/views/generic/base.py", line 73, in view
    return self.dispatch(request, *args, **kwargs)
  File "/opt/bitnami/python/lib/python3.8/site-packages/django/views/generic/base.py", line 101, in dispatch
    return handler(request, *args, **kwargs)
  File "/opt/bitnami/apps/django/django_projects/goFiles/uploads/views.py", line 18, in get
    return render(request, 'uploads/index.html', 'paste': paste)
  File "/opt/bitnami/python/lib/python3.8/site-packages/django/shortcuts.py", line 19, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "/opt/bitnami/python/lib/python3.8/site-packages/django/template/loader.py", line 62, in render_to_string
    return template.render(context, request)
  File "/opt/bitnami/python/lib/python3.8/site-packages/django/template/backends/django.py", line 63, in render
    reraise(exc, self.backend)
  File "/opt/bitnami/python/lib/python3.8/site-packages/django/template/backends/django.py", line 84, in reraise
    raise new from exc

Exception Type: TemplateDoesNotExist at /
Exception Value: uploads/base.html 

如果我需要提供更多信息,我很乐意这样做。任何帮助将不胜感激。

【问题讨论】:

设置'DIRS': ['/opt/bitnami/apps/django/django_projects/goFiles/uploads/templates/'], 【参考方案1】:

##django模板根目录可以使用子目录模板文件

settings.py

确保使用前定义的“BASE_DIR”

在项目内部构建路径,如下所示:BASE_DIR / 'subdir'。

BASE_DIR = Path(__file__).resolve().parent.parent

更新'DIRS':[BASE_DIR,'templates'],

TEMPLATES = [
    
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [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',
            ],
        ,
    ,
]

在您的项目根文件夹中创建模板目录。

在模板文件夹中创建子目录。 “blogs”是我的子目录

view.py

def post_list(request):
    posts = Post.published.all()
    return render(request,'blogs/post_list.html','posts':posts)

【讨论】:

【参考方案2】:

你在扩展的末尾添加了额外的空间,我手动尝试了 django 不允许任何额外的空间

from:
    % extends "uploads/base.html "% 
                                 ^
to:
    % extends "uploads/base.html" % 
                                 ^

【讨论】:

可以确认这是答案。您可以看到同一个错误多长时间而没有注意到让您生活地狱的一个空间,这是很疯狂的。 @kishan parmar 当我将文件模板/appname/index.html 文件移动到模板可怕根目录时遇到问题,它如何解决?

以上是关于存在模板时的 Django 3.1 TemplateNotFound 异常的主要内容,如果未能解决你的问题,请参考以下文章

Django 没有反向匹配错误 - 模板渲染

javascript中的Django模板实现?

Django框架之模板层template的一些介绍和使用

如何在 Django 模板中实现面包屑?

django 中的模板标签会执行两次吗?

django root url 不起作用