You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Django中的Template Does Not Exist错误?

解决Django模板不存在(Template Does Not Exist)500错误

核心问题分析

  1. 视图中模板路径冗余:render函数无需指定templates前缀,Django会自动从配置的模板目录中查找文件。
  2. 模板目录配置需匹配实际项目结构:需确保DIRS指向的路径与项目真实目录一致,同时利用APP_DIRS的自动搜索能力。

修正后的代码

1. views.py

from django.shortcuts import render
from django.http import HttpResponse

def home(request):
    # 直接使用模板相对路径,去掉templates前缀
    return render(request, 'home.html')

2. settings.py - 模板配置

根据你的项目结构调整,两种常见场景的配置如下:

场景1:模板放在项目根目录的templates文件夹

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [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',
            ],
        },
    },
]

场景2:模板放在子应用subokLang的templates文件夹

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

说明:APP_DIRS=True会让Django自动搜索所有已注册应用下的templates目录,只要subokLang在INSTALLED_APPS中,就无需额外配置DIRS。

3. urls.py(子应用)和根urls.py

这两个文件配置无问题,保持原样即可:

子应用urls.py

from django.urls import path

from . import views

urlpatterns = [ 
    path('', views.home, name='home')
]

根urls.py

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

urlpatterns = [
    path('', include('subokLang.urls')),
    path('admin/', admin.site.urls),
]

额外检查项

  • 确认home.html确实存在于你配置的模板目录中(比如根目录templates/或subokLang/templates/)。
  • 确保subokLang已添加到settings.py的INSTALLED_APPS列表:
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'subokLang',
]

内容的提问来源于stack exchange,提问作者Wyndham Keith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 07:45:19