简体   繁体   English

Django:TemplateDoesNotExist 在 /catalog/ 错误

[英]Django : TemplateDoesNotExist at /catalog/ error

I am a beginner at django and python and i am currently stuck at Creating our home page of the Django tutorial.我是 django 和 python 的初学者,目前我被困在创建我们的 Django 教程主页 I am getting a "TemplateDoesNotExist at error" error.我收到“TemplateDoesNotExist at error”错误。 I am also using windows.我也在用窗户。 What am I doing wrong?我究竟做错了什么?

Settings.py:设置.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/'

在此处输入图片说明

StackTrace:堆栈跟踪:

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: 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>

Views.py:视图.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)

index.html:索引.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 %}

If you want to place the template in-app level follow the directory structure like this如果您想将模板放置在应用程序级别,请遵循这样的目录结构

templates/<app_name>/your_template

Then in view.py use like this return render(request, '<app_name>/your_template', context=context)然后在view.py像这样使用 return render(request, '<app_name>/your_template', context=context)

If you want to place the template in root templates directory follow the structure like this如果要将模板放在根templates目录中,请遵循以下结构

templates/<app_name>/your_template

Then in view.py use like this然后在view.py像这样使用

return render(request, '<app_name>/your_template', context=context)
os.path.join(BASE_DIR, 'templates')

By this line of code you are adding that templates should be in your root folder of your project.通过这行代码,您将添加模板应位于项目的根文件夹中。 Create templates folder in your root directory of your project.在项目的根目录中创建templates文件夹。

templates directory in your project you should add in settings.py in TEMPLATES_DIRS like this项目中的templates目录,您应该像这样在TEMPLATES_DIRS中的settings.py添加

TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, "/localllibrary/templates"),
)

what it does is it will look for your created template ie index.html in directory specified here.它的作用是在此处指定的目录中查找您创建的模板,即index.html If you see it is a tuple or can be a list so you add multiple directories here.如果您看到它是一个元组或可以是一个列表,那么您可以在此处添加多个目录。 BASE_DIR is the root of you django project that is relative not hardcoded. BASE_DIR是你的 django 项目的根,它是相对的而不是硬编码的。

You file Structure should be like this:你的文件结构应该是这样的:

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

Now if your templates/static files is inside the templates/static folder at your project root, you can refer to them easily as someplace.html or css/somecss.css .现在,如果您的模板/静态文件位于项目根目录的模板/静态文件夹中,您可以轻松地将它们引用为someplace.htmlcss/somecss.css
While if it's inside the template folder in your app like this:如果它在您的应用程序中的模板文件夹中,则如下所示:

myApp --> templates --> myTemplate.html

Then you can use it like this: myTemplate.html .然后你可以像这样使用它: myTemplate.html But it's recommended to create another folder inside the templates folder with app name to avoid confusion, like this:但建议在模板文件夹中创建另一个文件夹,其中包含应用程序名称以避免混淆,如下所示:

myApp --> templates --> myApp --> myTemplate.html

Now you will refer to it like this: myApp/myTemplate.html , it avoids confusion as you will know from which app template is coming from, also it makes it possible to have templates with same name(say index.html or base.html ) in multiple apps.现在,您将像这样引用它: myApp/myTemplate.html ,它避免了混淆,因为您将知道来自哪个应用程序模板,还可以使用相同名称的模板(例如index.htmlbase.html ) 在多个应用程序中。 Same goes for static files.静态文件也是如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM