Django无法找到指定模板,错误查找不存在的post_list.html文件
Django TemplateDoesNotExist错误:未引用的core/post_list.html被查找,指定的home.html未被加载
你遇到的情况太典型了——明明在core应用的templates文件夹里只放了home.html,访问时却抛出TemplateDoesNotExist错误,提示找不到core/post_list.html,而且模板加载日志完全没提到你要渲染的home.html。先看看你的配置和代码细节:
你的配置与代码
settings.py
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', ] 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 = 'first_django.urls' 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', ], }, }, ]
views.py
from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Post class HomeView(ListView): model = Post template = "home.html"
core应用的urls.py
from django.urls import path from . import views from .views import HomeView urlpatterns = [ path('', HomeView.as_view(), name = "home"), ]
文件系统结构
├── core │ ├── templates │ │ └── home.html │ └── ... ├── first_django │ └── ... └── manage.py
问题根源
Django的ListView类视图有一个固定的属性名用来指定自定义模板:template_name。你在HomeView里错误地写成了template——这个属性名Django根本不识别!
当ListView找不到正确的template_name属性时,它会触发默认的模板路径规则:<app_name>/<model_name>_list.html。你的模型是Post,应用是core,所以Django就自动去寻找core/post_list.html,这就是为什么日志里完全没提到home.html——因为它根本没接收到你指定模板的指令!
修复方案
只需要把views.py里的template改成template_name即可:
from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Post class HomeView(ListView): model = Post template_name = "home.html" # 修正属性名
改完之后,Django就能正确识别你要使用的home.html模板,不会再去寻找默认的post_list.html了。
内容的提问来源于stack exchange,提问作者Yasmin Líbano
相关产品推荐
相关产品推荐

