本文主要解决Python的Django库在调用HTML文件时出现Template-loader postmortem的解决方法(见下图)!
请先看下图:图中hellohtml和hellospp是创建的app。mysite是在创建工程是生成的!
问题显示无法定位到HTML文件。在hellohtml文件下有views,py文件。有个叫做templates的文件夹,我的HTML文件放在该文件中。
1.我们需要在我们创建的app(这里是hellohtml)新建urls.py文件。添加如下。这里的from . import 中的“.”表示从当前路径导入views。views后面的hello是函数名,以你的为准!
from django.urls import pathfrom . import viewsurlpatterns=[ path('',views.hello),]2.我们需要更改mysite文件夹下的settings.py。找到settings.py文件中的TEMPLATES,加入代码os.path.join(BASE_DIR,'hellohtml/templates'),os.path.join用来连接路径,BASE_DIR表示当前路径,'hellohtml/templates'是HTML在相对路径下的路径!
TEMPLATES = [ { 'BACK': 'django.template.backs.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'hellohtml/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', ], }, },]3.找到mysite文件夹下的urls.py,在urlpatterns的列表中增加代码path('index2/',include('hellohtml.urls')),其中index2可以是其他名字,不要忘了后面的“/”,否则会出错。include需要导入from django.urls import include。hellohtml是你创建的app名,urls是第一步我们创建的。
urlpatterns = [ path('index2/',include('hellohtml.urls')), path('admin/', admin.site.urls),]4.在cmd命令下运行python manage.py runserver回车即可访问。如cmd提示OSError: [WinError 123] 文件名、目录名或卷标语法不正确。: '<frozen importlib._bootstrap>'。说明你的代码有问题,此时你是访问不成功的。正常会出现下面图框中的内容,此时即可成功访问html文件。
Watching for file changes with StatReloaderPerforming system checks...System check identified no issues (0 silenced).You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.Run 'python manage.py migrate' to apply them.May 14, 2021 - 20:16:13Django version 3.1.2, using settings 'mysite.settings'Starting development server at http://127.0.0.1:8000/Quit the server with CTRL-BREAK.下面的代码即可