Django类视图(Class Based Views)加载模板失败:TemplateDoesNotExist报错
Hey there! Let's dig into that TemplateDoesNotExist error you're facing with your Django Class-Based ListView. As someone who's walked dozens of new Django devs through this exact issue, I can tell you it's almost always tied to template configuration or path structure—let's break it down step by step.
settings.py Template Configuration First up, let's confirm the settings you suspected might be missing. Django relies on two key settings to find your app's templates:
a. Ensure Your App is in INSTALLED_APPS
Django will only look for templates in apps that are added to this list. Double-check that basic_app is included:
INSTALLED_APPS = [ # Default apps like 'django.contrib.admin', etc. 'basic_app', # **This line is critical—don't skip it!** ]
b. Check the TEMPLATES Block
Make sure APP_DIRS is set to True—this tells Django to automatically search the templates directory inside every installed app:
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], # Leave empty unless you have project-level templates 'APP_DIRS': True, # **Must be True for app-specific templates** 'OPTIONS': { 'context_processors': [ # Default context processors here ], }, }, ]
Django's ListView uses a default template naming convention: [app_name]/[model_name]_list.html (lowercase model name). For this to work, your template file must be nested correctly—this is the #1 mistake new devs make:
your_project_root/ └── basic_app/ └── templates/ └── basic_app/ # **Nested app directory is required!** └── yourmodel_list.html # Match your model's lowercase name + _list.html
If you skip the inner basic_app folder and put the template directly in basic_app/templates/, Django won't find it—it expects templates to be grouped under the app name inside the templates directory.
If you don't want to use Django's default naming rule, you can explicitly set the template path in your ListView:
from django.views.generic import ListView from .models import YourModel class YourListView(ListView): model = YourModel template_name = 'basic_app/your_custom_template.html' # Directly point to your template
Django sometimes caches template paths, so after making changes:
- Stop and restart your development server
- If you're on Django 3.2+, run this to clear template cache:
python manage.py clearcache - For older versions, delete any
__pycache__folders in your project.
- Double-check for typos: Filenames, app names, and paths are case-sensitive on Unix-based systems (Linux/macOS)
- Confirm the template file actually exists in the path you think it does—no missing files or misnamed folders!
内容的提问来源于stack exchange,提问作者Krishna

