【问题标题】:TemplateDoesNotExist even though the file existsTemplateDoesNotExist 即使文件存在
【发布时间】:2020-07-14 17:00:33
【问题描述】:

即使文件存在,我也会收到此错误 - 为什么?

编辑:

补充编辑:

from django.shortcuts import render

# Create your views here.

from catalog.models import Book, Author, BookInstance, Genre

def index(request):
    """View function for home page of site."""

    # Generate counts of some of the main objects
    num_books = Book.objects.all().count()
    num_instances = BookInstance.objects.all().count()

    # Available books (status = 'a')
    num_instances_available = BookInstance.objects.filter(status__exact='a').count()

    # The 'all()' is implied by default.    
    num_authors = Author.objects.count()

    context = {
        'num_books': num_books,
        'num_instances': num_instances,
        'num_instances_available': num_instances_available,
        'num_authors': num_authors,
    }

    # Render the HTML template index.html with the data in the context variable
    return render(request, 'index.html', context=context)

它说我写的不够多,代码太多,没有描述。所以我打字是为了绕过这个错误。

【问题讨论】:

  • 您没有提供足够的信息(没有 TEMPLATES 设置和 INSTALLED_APPS)。但我的上帝感觉 TEMPLATES 中的 APP_DIRS 设置设置为 False。
  • catalogINSTALLED_APPS 中吗?
  • @AntonPomieshchenko 编辑它们
  • @dirkgroten 是的。

标签: python django


【解决方案1】:

您的设置看起来是正确的,只是尽量不要提供目录。这可能是问题所在。这是我的一个项目的设置

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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 文件路径可能未指向您的位置。您可以在 Django 控制台中尝试此操作

激活你的虚拟环境$ source venv/bin/activate 然后运行python manage.py shell

在外壳中:

>>> from project.settings import TEMPLATES
>>> print(TEMPLATES['DIRS'])

输出是否指向您期望的位置?

===== 编辑

我看到 Django 正在 /catalog/ 中寻找您的模板,而实际上,您的模板实际上位于 app/catalog/templates/ 中,因此您的 DIRS 指令没有指向正确的路径。

如果您删除DIRS 中的目录,Django 将遍历您的目录目录,找到一个名为templates 的文件夹并找到您的index.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-25
    • 1970-01-01
    • 2015-07-15
    • 2019-01-04
    • 2017-02-01
    • 1970-01-01
    • 2018-11-16
    • 2021-04-30
    相关资源
    最近更新 更多