[英]Django : TemplateDoesNotExist at /catalog/ error
我是 django 和 python 的初學者,目前我被困在創建我們的 Django 教程主頁。 我收到“TemplateDoesNotExist at error”錯誤。 我也在用窗戶。 我究竟做錯了什么?
設置.py:
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
import os
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'cg#p$g+j9tax!#a3cup@1$8obt2_+&k3q+pmu)5%asj6yjpkag')
DEBUG = os.environ.get('DJANGO_DEBUG', '') != 'False'
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'catalog.apps.CatalogConfig',
]
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 = 'locallibrary.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(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',
],
},
},
]
WSGI_APPLICATION = 'locallibrary.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
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',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Chicago'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
堆棧跟蹤:
TemplateDoesNotExist at /catalog/
index.html
Request Method: GET
Request URL: http://127.0.0.1:8000/catalog/
Django Version: 2.1.5
Exception Type: TemplateDoesNotExist
Exception Value:
index.html
Exception Location: C:\Users\AjitGoel\Envs\my_django_environment\lib\site-packages\django\template\loader.py in get_template, line 19
Python Executable: C:\Users\AjitGoel\Envs\my_django_environment\Scripts\python.exe
Python Version: 3.7.2
Python Path:
['C:\\Users\\AjitGoel\\django-projects\\locallibrary',
'C:\\Users\\AjitGoel\\Envs\\my_django_environment\\Scripts\\python37.zip',
'C:\\Users\\AjitGoel\\Envs\\my_django_environment\\DLLs',
'C:\\Users\\AjitGoel\\Envs\\my_django_environment\\lib',
'C:\\Users\\AjitGoel\\Envs\\my_django_environment\\Scripts',
'c:\\users\\ajitgoel\\appdata\\local\\programs\\python\\python37\\Lib',
'c:\\users\\ajitgoel\\appdata\\local\\programs\\python\\python37\\DLLs',
'C:\\Users\\AjitGoel\\Envs\\my_django_environment',
'C:\\Users\\AjitGoel\\Envs\\my_django_environment\\lib\\site-packages']
Server time: Sun, 10 Feb 2019 23:21:43 -0600
Template-loader postmortem
Django tried loading these templates, in this order:
Using engine django:
django.template.loaders.filesystem.Loader: C:\Users\AjitGoel\django-projects\locallibrary\templates\index.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\AjitGoel\Envs\my_django_environment\lib\site-packages\django\contrib\admin\templates\index.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\AjitGoel\Envs\my_django_environment\lib\site-packages\django\contrib\auth\templates\index.html (Source does not exist)
base_generic.html:
<!DOCTYPE html>
<html lang="en">
<head>
{% block title %}<title>Local Library</title>{% endblock %}
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<!-- Add additional CSS in static file -->
{% load static %}
<link rel="stylesheet" href="{% static 'css/styles.css' %}">
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-sm-2">
{% block sidebar %}
<ul class="sidebar-nav">
<li><a href="{% url 'index' %}">Home</a></li>
<li><a href="">All books</a></li>
<li><a href="">All authors</a></li>
</ul>
{% endblock %}
</div>
<div class="col-sm-10 ">{% block content %}{% endblock %}</div>
</div>
</div>
</body>
</html>
視圖.py:
from django.shortcuts import render
from catalog.models import Book, Author, BookInstance, Genre
def index(request):
# Generate counts of some of the main objects
num_books = Book.objects.all().count()
num_instances = BookInstance.objects.all().count()
# Available books (status = 'a')
num_instances_available = BookInstance.objects.filter(status__exact='a').count()
# The 'all()' is implied by default.
num_authors = Author.objects.count()
context = {
'num_books': num_books,
'num_instances': num_instances,
'num_instances_available': num_instances_available,
'num_authors': num_authors,
}
# Render the HTML template index.html with the data in the context variable
return render(request, 'index.html', context=context)
索引.html:
{% extends "base_generic.html" %}
{% block content %}
<h1>Local Library Home</h1>
<p>Welcome to LocalLibrary, a website developed by <em>Mozilla Developer Network</em>!</p>
<h2>Dynamic content</h2>
<p>The library has the following record counts:</p>
<ul>
<li><strong>Books:</strong> {{ num_books }}</li>
<li><strong>Copies:</strong> {{ num_instances }}</li>
<li><strong>Copies available:</strong> {{ num_instances_available }}</li>
<li><strong>Authors:</strong> {{ num_authors }}</li>
</ul>
{% endblock %}
如果您想將模板放置在應用程序級別,請遵循這樣的目錄結構
templates/<app_name>/your_template
然后在view.py
像這樣使用 return render(request, '<app_name>/your_template', context=context)
如果要將模板放在根templates
目錄中,請遵循以下結構
templates/<app_name>/your_template
然后在view.py
像這樣使用
return render(request, '<app_name>/your_template', context=context)
os.path.join(BASE_DIR, 'templates')
通過這行代碼,您將添加模板應位於項目的根文件夾中。 在項目的根目錄中創建templates
文件夾。
項目中的templates
目錄,您應該像這樣在TEMPLATES_DIRS
中的settings.py
添加
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, "/localllibrary/templates"),
)
它的作用是在此處指定的目錄中查找您創建的模板,即index.html
。 如果您看到它是一個元組或可以是一個列表,那么您可以在此處添加多個目錄。 BASE_DIR
是你的 django 項目的根,它是相對的而不是硬編碼的。
你的文件結構應該是這樣的:
myProject
├── myProject
| ├── __init__.py
| ├── settings.py
| ├── urls.py
| ├── wsgi.py
├── myApp
| ├── static <-- Static files can go here
| | ├── myApp <-- Create a folder with the same name as the app name, recommended but not required
| | | ├── css
| | | | ├── style.css
| | | ├── js
| | | | ├── some.js
| ├── templates <-- Templates can be here
| | ├── myApp <-- Create a folder with the same name as the app name, recommended but not required
| | | ├── index.html
| | | ├── other.html
| ├── __init__.py
| ├── models.py
| ├── urls.py
| ├── views.py
├── templates <-- Templates can be here too
| ├── sometemplate.html
├── static <-- Static files can go here too
| ├── css
| | ├── somecss.css
| ├── js
現在,如果您的模板/靜態文件位於項目根目錄的模板/靜態文件夾中,您可以輕松地將它們引用為someplace.html
或css/somecss.css
。
如果它在您的應用程序中的模板文件夾中,則如下所示:
myApp --> templates --> myTemplate.html
然后你可以像這樣使用它: myTemplate.html
。 但建議在模板文件夾中創建另一個文件夾,其中包含應用程序名稱以避免混淆,如下所示:
myApp --> templates --> myApp --> myTemplate.html
現在,您將像這樣引用它: myApp/myTemplate.html
,它避免了混淆,因為您將知道來自哪個應用程序模板,還可以使用相同名稱的模板(例如index.html
或base.html
) 在多個應用程序中。 靜態文件也是如此。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.