【问题标题】:Django tries to find template in a non-existing folderDjango 尝试在不存在的文件夹中查找模板
【发布时间】:2020-03-23 14:10:17
【问题描述】:

我是 Django 新手,我正在关注https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django 的指南。所以我想我会跟随但不完全复制代码。

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

当我尝试访问 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/

    |     |

    |     -- 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/'

我的目录/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"),
]

我的目录/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

在过去的几个小时里,我一直在试图找出我的错误,但除了在不知道原因的情况下接受模板将位于“目录/模板/目录/”中之外,没有任何效果。

【问题讨论】:

    标签: django django-templates django-settings


    【解决方案1】:
    # 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
    

    【讨论】:

    • 它有效,但知道为什么它必须在“目录/”内,是否可以更改此要求?
    • 它必须在“目录”中,因为它是您的 views.py 类被调用的应用程序名称。是的,它可以通过在你的views.py类中定义template_name来改变。
    猜你喜欢
    • 1970-01-01
    • 2018-10-22
    • 1970-01-01
    • 2016-11-17
    • 2019-01-02
    • 1970-01-01
    • 2021-04-18
    • 2013-03-02
    • 2018-04-17
    相关资源
    最近更新 更多