我尝试从本教程中学习Django CRUD: https://www.javatpoint.com/django-crud-example 我的Django版本是2.1.7,IDE是VisualStudio。 当我运行项目时,所有页面都有错误。错误传来了。
TemplateDoesNotExist at /index
show.html
Request Method: GET
Request URL: http://localhost:52322/index
Django Version: 2.1.7
Exception Type: TemplateDoesNotExist
Exception Value:
show.html
Exception Location: E:\Django_Try\DjangoWebProject5\DjangoWebProject5\env\lib\site-packages\django\template\loader.py in get_template, line 19
Python Executable: E:\Django_Try\DjangoWebProject5\DjangoWebProject5\env\Scripts\python.exe
Python Version: 3.6.6
Python Path:
['E:\\Django_Try\\DjangoWebProject5\\DjangoWebProject5',
'',
'E:\\Django_Try\\DjangoWebProject5\\DjangoWebProject5',
'E:\\Django_Try\\DjangoWebProject5\\DjangoWebProject5\\env\\Scripts\\python36.zip',
'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_64\\DLLs',
'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_64\\lib',
'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_64',
'E:\\Django_Try\\DjangoWebProject5\\DjangoWebProject5\\env',
'E:\\Django_Try\\DjangoWebProject5\\DjangoWebProject5\\env\\lib\\site-packages']
Server time: Tue, 5 Mar 2019 22:43:24 +0000
我在下面添加我的Urls波纹管
from django.conf.urls import include, url
from django.contrib import admin
from django.urls import path
from employee import views
urlpatterns = [
path('index', views.show),
path('admin/', admin.site.urls),
path('emp', views.emp),
path('show',views.show),
path('edit/<int:id>', views.edit),
path('update/<int:id>', views.update),
path('delete/<int:id>', views.destroy),
]
查看:
from django.shortcuts import render, redirect
from employee.forms import EmployeeForm
from employee.models import Employee
# Create your views here.
def emp(request):
if request.method == "POST":
form = EmployeeForm(request.POST)
if form.is_valid():
try:
form.save()
return redirect('/show')
except:
pass
else:
form = EmployeeForm()
return render(request,'index.html',{'form':form})
def show(request):
employees = Employee.objects.all()
return render(request,"show.html",{'employees':employees})
def edit(request, id):
employee = Employee.objects.get(id=id)
return render(request,'edit.html', {'employee':employee})
def update(request, id):
employee = Employee.objects.get(id=id)
form = EmployeeForm(request.POST, instance = employee)
if form.is_valid():
form.save()
return redirect("/show")
return render(request, 'edit.html', {'employee': employee})
def destroy(request, id):
employee = Employee.objects.get(id=id)
employee.delete()
return redirect("/show")
设置:
"""
Django settings for DjangoWebProject5 project.
Generated by 'django-admin startproject' using Django 1.9.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
import posixpath
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '65ccf984-10e5-4c13-ab4d-9c0cf30e8b04'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
# Add your apps here to enable them
'employee',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'DjangoWebProject5.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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 = 'DjangoWebProject5.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.9/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/1.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = posixpath.join(*(BASE_DIR.split(os.path.sep) + ['static']))
项目结构完全类似于下面的图像教程:
https://www.javatpoint.com/django/images/django-crud-example-project-structure.png
我的结构屏幕截图:
https://drive.google.com/open?id=1xRB0xcnkplZ4ktiyEblkMVeyJ1SpATDc
我认为该错误表明模板不存在,但模板存在。 请通知我我的应用程序有什么问题。
答案 0 :(得分:0)
在您的settings.py
文件中,模板目录需要分配为:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['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',
],
},
},
]
类似地,确保模板具有以下结构:
|-app_name
|-templates
|-app_name
|-show.html
|-index.html and so on
答案 1 :(得分:0)
对不起,我无法访问您的目录屏幕截图,我认为这是由于我的阻止。 Sanip(我认为)是正确的答案。在学习Django如何查找和使用模板方面有很多困难时,我的元技巧是继续尝试。只有这么多错误的做事方式。例如,您可以创建一组“ show.html”文件,仅包含其所在目录的声明,然后将其放在项目中的每个目录中。 例如 在项目根文件夹中:
# show.html
<p> project root </p>
在新的“模板”文件夹中:
# employees/templates/show.html
<p> this one is in employees/templates/show.html
您实际上不需要这样做,但是,如果事情没有解决,就没有害处。需要5分钟,您才能找到Django正在寻找并重置的地方。
您的模板“ show.html”应位于应用程序“员工”的名为“模板”的子目录中。我的settings.py具有'DIRS':['/ templates /']和'APP_DIRS':True。结果,Django在我所有的应用程序目录中寻找一个名为“ templates”的文件夹。当我在views.py中引用模板时,Django会在我的所有应用程序中(从列表的开头开始)查找/ templates /。如果愿意,可以在一个模板目录中包含子目录,这是确保您不会意外为下一个应用程序调用错误模板的好方法。
文档:https://docs.djangoproject.com/en/2.1/ref/settings/#std:setting-TEMPLATES-DIRS