简体   繁体   English

为什么Django无法找到正确的模板

[英]Why Django can't find the right templates

I try to learn Django CRUD from this tutorial: https://www.javatpoint.com/django-crud-example My Django version is 2.1.7 and my IDE is VisualStudio. 我尝试从本教程中学习Django CRUD: https : //www.javatpoint.com/django-crud-example我的Django版本是2.1.7,IDE是VisualStudio。 When I run the project all the pages have an error. 当我运行项目时,所有页面都有错误。 the error cames bellow. 错误来了。

 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

I added my Urls bellow: 我添加了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),  
]

View: 视图:

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") 

setting: 设置:

"""
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']))

My structure screenshot: 我的结构截图:

https://drive.google.com/open?id=1xRB0xcnkplZ4ktiyEblkMVeyJ1SpATDc https://drive.google.com/open?id=1xRB0xcnkplZ4ktiyEblkMVeyJ1SpATDc

I think the error says the template does not exist but the templates exist. 我认为错误表明模板不存在,但模板存在。 Please inform me what is wrong in my application. 请告知我我的申请有什么问题。

Here, your troubles come from your understanding of your project architecture. 在这里,您的麻烦来自对项目体系结构的了解。 As you can see in your screenshoot here 正如您在此处的屏幕快照中所看到的

Your template files are in the */DjangoWebProject5/employee/templates/ employee/ 您的模板文件位于* / DjangoWebProject5 / employee / templates / employee /

So you have too call them with the right path like 'employee/index.html' 因此,您也可以使用正确的路径来称呼他们,例如“ employee / index.html”

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,'employee/index.html',{'form':form})  ## Here 'employee/index.html'

You can fix that on all your views. 您可以在所有视图上修复该问题。

Check this 检查一下

It appears that TEMPLATE_DIRS was used prior to 1.8 but in the current version it has changed to a DIRS option in the TEMPLATES setting. 看起来TEMPLATE_DIRS是在1.8之前使用的,但在当前版本中,它已在TEMPLATES设置中更改为DIRS选项。

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [
        '/home/html/templates/lawrence.com',
        '/home/html/templates/default',
    ],
},

]

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

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