【问题标题】:how to fix template does not exist in Django?如何修复 Django 中不存在的模板?
【发布时间】:2022-01-23 12:26:43
【问题描述】:

我是 Django 框架的初学者。我创建了我的项目并创建了我的应用程序并对其进行了测试,在我决定添加模板之前它工作正常。我不知道错误来自哪里,因为我遵循 Django 文档所说的方法,在您的应用程序文件夹中创建文件夹名称模板,使用您的应用程序名称创建一个文件夹,最后在该文件夹中创建 HTML 文件。

注意:除模板外,其他路线都可以正常工作

请在下面查看我的文件结构和错误的屏幕截图。 File Structure

错误

    TemplateDoesNotExist at /blog/
 Blog/index
Request Method: GET
Request URL:    http://127.0.0.1:8000/blog/
Django Version: 4.0.1
Exception Type: TemplateDoesNotExist
Exception Value:    
 Blog/index
Exception Location: C:\Python39\lib\site-packages\django\template\loader.py, line 19, in get_template
Python Executable:  C:\Python39\python.exe
Python Version: 3.9.4
Python Path:    
['C:\\Users\\Maxwell\\Desktop\\Django\\WebApp',
 'C:\\Python39\\python39.zip',
 'C:\\Python39\\DLLs',
 'C:\\Python39\\lib',
 'C:\\Python39',
 'C:\\Users\\Maxwell\\AppData\\Roaming\\Python\\Python39\\site-packages',
 'C:\\Python39\\lib\\site-packages',
 'C:\\Python39\\lib\\site-packages\\win32',
 'C:\\Python39\\lib\\site-packages\\win32\\lib',
 'C:\\Python39\\lib\\site-packages\\Pythonwin']
Server time:    Sun, 23 Jan 2022 12:04:18 +0000
Template-loader postmortem
Django tried loading these templates, in this order:

Using engine django:

django.template.loaders.app_directories.Loader: C:\Users\Maxwell\Desktop\Django\WebApp\Blog\templates\ Blog\index (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Python39\lib\site-packages\django\contrib\admin\templates\ Blog\index (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Python39\lib\site-packages\django\contrib\auth\templates\ Blog\index (Source does not exist)

App/views.py

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

# Create your views here.

def index(request,name):
    return HttpResponse(f'Hello {name}')

def html(request):
    return render(request,' Blog/index.html')

【问题讨论】:

  • 分享相关观点。

标签: python django


【解决方案1】:

看起来你用Blog/index渲染模板,但是你需要指定整个文件名,所以Blog/index.html没有前导(或尾随)空格:

def html(request):
    return render(request, 'Blog/index.html')

【讨论】:

  • 它已经存在但仍然无法正常工作
  • @MaxwellD.Dorliea:模板名称中还有一个前导空格,'Blog/index.html',而不是' Blog/index.html'。但异常清楚地表明它是在没有 .html 扩展名的情况下触发的。
【解决方案2】:

如果@Willem van Onsem 的回答无效

在主目录'与WebApp同级'中创建一个模板文件夹 然后在其中为每个应用创建文件夹

在您的 settings.py 中,您会找到 TEMPLATES 选项

TEMPLATES = [
    {
        ...
        'DIRS': [os.path.join(BASE_DIR,'templates')],#add this line
        ...
]

当你想使用模板时

return render(request,"template_folder/template_name.html")

【讨论】:

  • 模板不是写在根目录下的templates/,而是应用的templates/,所以要求APP_DIRSTrue
猜你喜欢
  • 1970-01-01
  • 2020-09-28
  • 2012-08-19
  • 2019-12-19
  • 2019-09-13
  • 2015-10-06
  • 1970-01-01
  • 2017-01-23
  • 2010-12-27
相关资源
最近更新 更多