Django 尝试在不存在的文件夹中查找模板

Django tries to find template in a non-existing folder

我是 Django 的新手,我正在按照 https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django 上的指南进行操作。所以我想我会跟进但不会完全复制代码。

我一定是犯了一些基本错误,但我想不通。我阅读了许多描述类似问题的线程,但 none 解决了我的问题。

当我尝试访问 index.html 以外的任何页面时,我收到此错误消息:

TemplateDoesNotExist at /catalog/livros/
catalog/livro_list.html

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

Using engine django:

django.template.loaders.filesystem.Loader: C:\Users\Gledyson\PROJECTS\Websites\Library\templates\catalog\livro_list.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\Gledyson\PROJECTS\Websites\Library\myvenv\lib\site-packages\django\contrib\admin\templates\catalog\livro_list.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\Gledyson\PROJECTS\Websites\Library\myvenv\lib\site-packages\django\contrib\auth\templates\catalog\livro_list.html (Source does not exist)

Django 试图在 'templates/catalog/' 而不是 'templates/' 中查找我的模板。我尝试将我的模板移动到 'library/catalog/templates/catalog/' 并且它有效。但是我无法让它在 'library/templates'.

中找到我的模板

我的项目树看起来有点像这样:

Library/

    |

    -- catalog/

    |     |

    |     -- static/, admin.py, apps.py, models.py, tests.py, urls.py, views.py

    |    

    -- locallibrary/

    |     |

    |     -- settings.py, urls.py, wsgi.py

    -- myvenv/

    |

    -- templates/

           |

           -- base.html, index.html, livro_detail.html, livro_list.html

我的 locallibrary/settings.py 是:

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'EDITED'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'catalog',
]

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.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'locallibrary.urls'

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

WSGI_APPLICATION = 'locallibrary.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/

LANGUAGE_CODE = 'pt-br'

TIME_ZONE = 'America/Campo_Grande'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = '/static/'

我的catalog/urls.py:

from django.contrib import admin
from django.urls import path, include, re_path
from . import views


urlpatterns = [
    path('', views.index, name='index'),
    # path('lista_de_livros/', views.lista_de_livros, name="lista_de_livros"),
    path('livros/', views.ListaDeLivros.as_view(), name="livros"),
    re_path(r'^livro/(?P<pk>\d+)$', views.DetalhesDoLivro.as_view(), name="detalhe-livro"),
]

我的catalog/views.py:

from django.shortcuts import render, get_object_or_404, redirect
from .models import Gênero, Idioma, Livro, LivroInstância, Autor
from django.views import generic

# Create your views here.
def index(request):

    num_livros = Livro.objects.all().count()
    num_instâncias = LivroInstância.objects.all().count()
    num_instâncias_disponíveis = LivroInstância.objects.filter(estado__exact='d').count() #Livros disponíveis (estado == 'd')
    num_autores = Autor.objects.all().count()
    num_gêneros = Gênero.objects.all().count()
    num_livros_maionese = Livro.objects.filter(título__icontains='maionese').count()

    context = {
        'num_livros': num_livros,
        'num_instâncias': num_instâncias,
        'num_instâncias_disponíveis': num_instâncias_disponíveis,
        'num_autores': num_autores,
        'num_gêneros': num_gêneros,
        'num_livros_maionese': num_livros_maionese,
    }

    return render(request, 'index.html', context=context)

# def lista_de_livros(request):
#     lista_de_livros = Livro.objects.all()
#     return render(request, 'lista_de_livros.html', {'lista_de_livros' : lista_de_livros})
class ListaDeLivros(generic.ListView):
    model = Livro

class DetalhesDoLivro(generic.DetailView):
    model = Livro

过去几个小时我一直在努力寻找我的错误,但除了接受模板将在 'catalog/templates/catalog/' 中之外没有任何效果,但不知道为什么。

# You need to create 'catalog' folder in your template folder. And keep your 'livro_list.html' template inside that folder. Or else you can define your template location in your template_name variable of your class 'ListaDeLivros'


class ListaDeLivros(generic.ListView):
    template_name = 'livro_list.html'  # you can define your path here
    model = Livro