如何在运行Django 4.2服务器时解决’TemplateDoesNotExist’错误?

huangapple go评论71阅读模式
英文:

How to solve 'TemplateDoesNotExist' error in Django 4.2 while running the server?

问题

这是一个Django项目中的错误信息,表明找不到名为 "home.html" 的模板文件。您可能需要检查以下几点以解决此问题:

  1. 确保 "home.html" 文件存在于您的模板文件夹中。根据您的目录结构,它应该在 "F:\Django\geekshows\templates" 目录中。

  2. 确保在您的视图或模板中正确引用了 "home.html"。在您的视图函数中,使用 render 函数的第一个参数应该是模板文件的路径,确保路径是正确的。

  3. 检查您的Django配置。确保您的Django项目设置中的 TEMPLATES 部分已正确配置,包括 'APP_DIRS': True 以便查找应用程序目录中的模板。

  4. 如果您最近修改了模板文件或项目结构,请确保重新启动Django开发服务器,以便使更改生效。

请仔细检查这些方面,以确保 "home.html" 模板文件被正确引用和定位。

英文:
TemplateDoesNotExist at /
home.html
Request Method:	GET
Request URL:	http://127.0.0.1:5555/
Django Version:	4.2.1
Exception Type:	TemplateDoesNotExist
Exception Value:	
home.html
Exception Location:	C:\Users\soumy\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\template\loader.py, line 19, in get_template
Raised during:	geekshows.views.home
Python Executable:	C:\Users\soumy\AppData\Local\Programs\Python\Python311\python.exe
Python Version:	3.11.3
Python Path:	
['F:\\Django\\geekshows',
 'C:\\Users\\soumy\\AppData\\Local\\Programs\\Python\\Python311\\python311.zip',
 'C:\\Users\\soumy\\AppData\\Local\\Programs\\Python\\Python311\\DLLs',
 'C:\\Users\\soumy\\AppData\\Local\\Programs\\Python\\Python311\\Lib',
 'C:\\Users\\soumy\\AppData\\Local\\Programs\\Python\\Python311',
 'C:\\Users\\soumy\\AppData\\Roaming\\Python\\Python311\\site-packages',
 'C:\\Users\\soumy\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages']
Server time:	Mon, 22 May 2023 13:56:05 +0000

Template-loader postmortem
Django tried loading these templates, in this order:

Using engine django:

django.template.loaders.filesystem.Loader: F:\Django\geekshows\templates\home.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\soumy\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\admin\templates\home.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\soumy\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\auth\templates\home.html (Source does not exist)
django.template.loaders.app_directories.Loader: F:\Django\geekshows\course\templates\home.html (Source does not exist)
django.template.loaders.app_directories.Loader: F:\Django\geekshows\fees\templates\home.html (Source does not exist)

When I am running server this error is comming. I am using Django 4.2 so how to over come.


Folder Structure:

F:\Django\geekshows
course folder and fees folder

fees and geekshows folder

1. course\templates\course\course1.html

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
    &lt;title&gt;Document&lt;/title&gt;
&lt;/head&gt;

&lt;body&gt;
    &lt;h3&gt;Hello {{nm}}&lt;/h3&gt;
&lt;/body&gt;
&lt;/html&gt;

<!-- end snippet -->

2. course\templates\course\course2.html

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
    &lt;title&gt;Document&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;h1&gt;Hello Python&lt;/h1&gt;
&lt;/body&gt;
&lt;/html&gt;

<!-- end snippet -->

3. course\urls.py

from django.urls import path
# from course.views import learn_django
# from fees.views import fees_django
from . import views

urlpatterns = [
    path(&#39;learndj/&#39;, views.learn_django),
    path(&#39;learnpy/&#39;, views.learn_python)
]

4. course\views.py

from django.shortcuts import render
from django.http import HttpResponse
from datetime import datetime
# Create your views here.

def learn_django(request):
    return render(request, &#39;course/course1.html&#39;, {&#39;nm&#39;:&#39;Django&#39;})

def learn_python(request):
    return render(request, &#39;course/course2.html&#39;)

答案1

得分: 1

你似乎有一个名为home的视图,渲染home.html,但找不到home.html

Raised during: geekshows.views.home
...
django.template.loaders.filesystem.Loader: F:\Django\geekshows\templates\home.html (Source does not exist)

请注意,你的应用结构似乎不符合标准,视图文件应该在应用程序内(比如.../geekshows/main/views.py),但你的似乎在项目根文件夹geekshows中。

标准结构:
geekshows/ # 项目根目录
main/ # 应用程序 main(或其他名称)
templates/
main/
home.html
models.py
views.py
...
course/ # 应用程序 course
fees/ # 应用程序 fees
geekshows/ # 与项目同名的文件夹 -> Django 请求的入口点
urls.py
wsgi.py
settings.py
manage.py

请发布视图并显示放置home.html的文件夹结构,以进一步回答你的问题。

英文:

you seem to have a view home that renders home.html but home.html cant be found

Raised during:  geekshows.views.home
...
django.template.loaders.filesystem.Loader: F:\Django\geekshows\templates\home.html (Source does not exist)

please note that you seem to have a non standard structure of your app as a view file should be inside an app (like .../geekshows/main/views.py) but yours seems to be in the project root folder geekshows.

standard structure:

geekshows/                      # project root
   main/                        # app main (or another name)
      templates/
          main/
             home.html
      models.py
      views.py
      ...
   course/                      # app course
   fees/                        # app fees
   geekshows/                   # folder with same name as project -&gt; django entry point for requests
      urls.py
      wsgi.py
      settings.py
   manage.py

please post the view and show the folder structure where you placed home.html to further answer your question

答案2

得分: 0

Sure, here are the translated parts:

5. geekshows\templates\home.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h3>Home {{name}}</h3>
</body>
</html>

6. geekshows\settings.py

"""
Django settings for geekshows project.

Generated by 'django-admin startproject' using Django 4.2.1.

For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATES_DIR = BASE_DIR / "templates"

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-0q$2kj0_mvxvfz!w((9#-qp+_ceqkdcl+g9^_zq^c$7$ew1h&y'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'course',
    'fees',
    'result',
]

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 = 'geekshows.urls'

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

WSGI_APPLICATION = 'geekshows.wsgi.application'

# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

7. geekshows\urls.py

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('cor/', include('course.urls')),
    path('fe/', include('fees.urls')),
    path('', views.home),
]

8. geekshows\views.py

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

def home(request):
    return render(request, 'home.html', {'name':'Page'})

Please note that the code and HTML content have been translated as requested, and there are no additional comments or explanations.

英文:

This is a answer to Razenstein

5. geekshows\templates\home.html

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;UTF-8&quot;&gt;
&lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt;
&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
&lt;title&gt;Document&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h3&gt;Home {{name}}&lt;/h3&gt;
&lt;/body&gt;
&lt;/html&gt;

6. geekshows\settings.py

&quot;&quot;&quot;
Django settings for geekshows project.
Generated by &#39;django-admin startproject&#39; using Django 4.2.1.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
&quot;&quot;&quot;
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / &#39;subdir&#39;.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATES_DIR =  BASE_DIR / &quot;templates&quot;
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = &#39;django-insecure-0q$2kj0_mvxvfz!w((9#-qp+_ceqkdcl+g9^_zq^c$7$ew1h&amp;y&#39;
# SECURITY WARNING: don&#39;t run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
&#39;django.contrib.admin&#39;,
&#39;django.contrib.auth&#39;,
&#39;django.contrib.contenttypes&#39;,
&#39;django.contrib.sessions&#39;,
&#39;django.contrib.messages&#39;,
&#39;django.contrib.staticfiles&#39;,
&#39;course&#39;,
&#39;fees&#39;,
&#39;result&#39;,
]
MIDDLEWARE = [
&#39;django.middleware.security.SecurityMiddleware&#39;,
&#39;django.contrib.sessions.middleware.SessionMiddleware&#39;,
&#39;django.middleware.common.CommonMiddleware&#39;,
&#39;django.middleware.csrf.CsrfViewMiddleware&#39;,
&#39;django.contrib.auth.middleware.AuthenticationMiddleware&#39;,
&#39;django.contrib.messages.middleware.MessageMiddleware&#39;,
&#39;django.middleware.clickjacking.XFrameOptionsMiddleware&#39;,
]
ROOT_URLCONF = &#39;geekshows.urls&#39;
TEMPLATES = [
{
&#39;BACKEND&#39;: &#39;django.template.backends.django.DjangoTemplates&#39;,
&#39;DIRS&#39;: [TEMPLATES_DIR],
&#39;APP_DIRS&#39;: True,
&#39;OPTIONS&#39;: {
&#39;context_processors&#39;: [
&#39;django.template.context_processors.debug&#39;,
&#39;django.template.context_processors.request&#39;,
&#39;django.contrib.auth.context_processors.auth&#39;,
&#39;django.contrib.messages.context_processors.messages&#39;,
],
},
},
]
WSGI_APPLICATION = &#39;geekshows.wsgi.application&#39;
# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
DATABASES = {
&#39;default&#39;: {
&#39;ENGINE&#39;: &#39;django.db.backends.sqlite3&#39;,
&#39;NAME&#39;: BASE_DIR / &#39;db.sqlite3&#39;,
}
}
# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
&#39;NAME&#39;: &#39;django.contrib.auth.password_validation.UserAttributeSimilarityValidator&#39;,
},
{
&#39;NAME&#39;: &#39;django.contrib.auth.password_validation.MinimumLengthValidator&#39;,
},
{
&#39;NAME&#39;: &#39;django.contrib.auth.password_validation.CommonPasswordValidator&#39;,
},
{
&#39;NAME&#39;: &#39;django.contrib.auth.password_validation.NumericPasswordValidator&#39;,
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/
LANGUAGE_CODE = &#39;en-us&#39;
TIME_ZONE = &#39;UTC&#39;
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/
STATIC_URL = &#39;static/&#39;
# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = &#39;django.db.models.BigAutoField&#39;

7. geekshows\urls.py

from django.contrib import admin
from django.urls import path, include
from . import views
urlpatterns = [
path(&#39;admin/&#39;, admin.site.urls),
path(&#39;cor/&#39;, include(&#39;course.urls&#39;)),
path(&#39;fe/&#39;, include(&#39;fees.urls&#39;)),
path(&#39;&#39;, views.home),
]

8. geekshows\views.py

from django.shortcuts import render
from django.http import HttpResponse
def home(request):
return render(request, &#39;home.html&#39;, {&#39;name&#39;:&#39;Page&#39;})

huangapple
  • 本文由 发表于 2023年5月22日 22:11:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76307080.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定