TemplateDoesNotExist,即使文件存在

2024-05-19 21:38:51 发布

您现在位置:Python中文网/ 问答频道 /正文

enter image description here

即使文件存在,我也会出现此错误-为什么

enter image description here

编辑:

enter image description here

enter image description here

附加编辑:

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)

它说我写得不够,代码太多,没有描述。因此,我正在键入以绕过此错误


Tags: oftheinstances编辑indexobjectscount错误
1条回答
网友
1楼 · 发布于 2024-05-19 21:38:51

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

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

相关问题 更多 >