关于Django错误消息TemplateDoesNotExist在/

时间:2017-09-05 16:23:28

标签: django django-views

我正在尝试通过Django为博客申请,但不会显示首页(post_list.html)。 将显示以下错误消息。

 TemplateDoesNotExist at /
 blogapp3/post_list.html
 Request Method:    GET
 Request URL:   http://127.0.0.1:8000/
 Django Version:    1.11.4
 Exception Type:    TemplateDoesNotExist
 Exception Value:   
 blogapp3/post_list.html
 Exception Location:    F:\01_pro\kaso3\lib\site-packages\django\template\loader.py in select_template, line 53
 Python Executable: F:\01_pro\kaso3\Scripts\python.exe
 Python Version:    3.6.2

 Template-loader postmortem

 Django tried loading these templates, in this order:

 Using engine django:
 django.template.loaders.filesystem.Loader: F:\01_pro\blogpro3\blogapp3\templates\blog\blogapp3\post_list.html (Source does not exist)
django.template.loaders.app_directories.Loader: F:\01_pro\kaso3\lib\site-packages\django\contrib\admin\templates\blogapp3\post_list.html (Source does not exist)
django.template.loaders.app_directories.Loader: F:\01_pro\kaso3\lib\site-packages\django\contrib\auth\templates\blogapp3\post_list.html (Source does not exist)
django.template.loaders.app_directories.Loader: F:\01_pro\blogpro3\blogapp3\templates\blogapp3\post_list.html (Source does not exist)

我曾被指出其他网站的文件结构错误,但我认为这个文件似乎并不奇怪。文件结构如下。

F:\01_PRO\BLOGPRO3
│  db.sqlite3
│  manage.py
│
├─blogapp3
│  │  admin.py
│  │  apps.py
│  │  forms.py
│  │  models.py
│  │  tests.py
│  │  urls.py
│  │  views.py
│  │  __init__.py
│  │
│  ├─migrations
│  │  │  0001_initial.py
│  │  |  0002_auto_20170905_1930.py
│  │  └─  __init__.py
│  │
│  │
│  ├─static
│  │  ├─css
│  │  │      blog.css
│  │  │
│  │  └─js
│  │
│  └─templates
│     ├─blog
│     │      about.html
│     │      base.html
│     │      comment_form.html
│     │      post_confirm_delete.html
│     │      post_detail.html
│     │      post_draft_list.html
│     │      post_form.html
│     │      post_list.html
│     │
│     └─registration
│            login.html
│
│
└─blogpro3
       settings.py
       urls.py
       wsgi.py
       __init__.py

下面,我会显示urls.pyviews.pysettings.py以解决此问题。

blogpro3/urls.py

from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.auth import views

urlpatterns = [
    url(r'^admin/',admin.site.urls),
    url(r'',include('blogapp3.urls')),
    url(r'^accounts/login/$', views.login, name='login'),
    url(r'^accounts/logout/$', views.logout, name='logout', kwargs={'next_page': '/'}),
]

blogapp3/urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$',views.PostListView.as_view(), name='post_list'),
    url(r'^about/$',views.AboutView.as_view(),name='about'),
    url(r'^post/(?P<pk>\d+)$',views.PostDetailView.as_view(),name='post_detail'),
    url(r'^post/new/$',views.CreatePostView.as_view(),name='post_new'),
    url(r'^post/(?P<pk>\d+)/edit/$',views.PostUpdateView.as_view(),name='post_edit'),
    url(r'^post/(?P<pk>\d+)/remove/$',views.PostDetailView.as_view(),name='post_remove'),
    url(r'^drafts/$',views.DraftListView.as_view(),name='post_draft_list'),
    url(r'^post/(?P<pk>\d+)/comment/$',views.add_comment_to_post,name='add_comment_to_post'),
    url(r'^comment/(?P<pk>\d+)/approve/$',views.comment_approve,name='comment_approve'),
    url(r'^comment/(?P<pk>\d+)/remove/$',views.comment_remove,name='comment_remove'),
    url(r'^post/(?P<pk>\d+)/publish/$',views.post_publish,name='post_publish'),
]

views.py

from django.shortcuts import render,get_object_or_404,redirect
from django.contrib.auth.decorators import login_required
from blogapp3.models import Post,Comment
from django.utils import timezone
from blogapp3.forms import PostForm,CommentForm

from django.views.generic import (TemplateView,ListView,
                                  DetailView,CreateView,
                                  UpdateView,DeleteView)

from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin

# Create your views here.

class AboutView(TemplateView):
    template_name = 'about.html'

class PostListView(ListView):
    model = Post

    def get_queryset(self):
        return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')

class PostDetailView(DetailView):
    model = Post

class CreatePostView(LoginRequiredMixin,CreateView):
    login_url = '/login/'
    redirect_field_name = 'blog/post_detail.html'

    form_class = PostForm
    model = Post

class PostUpdateView(LoginRequiredMixin,UpdateView):
    login_url = '/login/'
    redirect_field_name = 'blog/post_detail.html'

    form_class = PostForm
    model = Post

class PostDleteView(LoginRequiredMixin,DeleteView):
    model = Post
    success_url = reverse_lazy('post_list')

class DraftListView(LoginRequiredMixin,ListView):
    login_url = '/login/'
    redirect_field_name = 'blog/post_list.html'
    model = Post

    def get_queryset(self):
        return Post.objects.filter(published_date__isnull=True).order_by('created_date')

##################################
##################################

@login_required
def post_publish(request,pk):
    post = get_object_or_404(Post,pk=pk)
    post.publish()
    return redirect('post_detail',pk=pk)



@login_required
def add_comment_to_post(request,pk):
    post = get_object_or_404(Post,pk=pk)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.save()
            return redirect('post_detail',pk=post.pk)
    else:
        form = CommentForm()
    return render(request,'blog/comment_form.html',{'form':form})

@login_required
def comment_approve(request,pk):
    comment = get_object_or_404(Comment,pk=pk)
    comment.approve()
    return redirect('post_detail',pk=comment.post.pk)

@login_required
def comment_remove(request,pk):
    comment = get_object_or_404(Comment,pk=pk)
    post_pk = comment.post.pk
    comment.delete()
    return redirect('post_detail',pk=post_pk)

settings.py

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIRS = os.path.join(BASE_DIR,'blogapp3/templates/blog')

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

# 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',
    'blogapp3.apps.BlogappConfig',
]

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

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_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 = 'blogpro3.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.11/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.11/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.11/topics/i18n/

LANGUAGE_CODE = 'ja'

TIME_ZONE = 'Asia/Tokyo'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'Static')

LOGIN_REDIRECT_URL = '/'

TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates'),)

我要注意的是错误消息中的以下部分。

Template-loader postmortem

 Django tried loading these templates, in this order:

 Using engine django:
 django.template.loaders.filesystem.Loader: F:\01_pro\blogpro3\blogapp3\templates\blog\blogapp3\post_list.html (Source does not exist)

上述路径应该适用于以下路径。

  

F:\ 01_pro \ blogpro3 \ blogapp3 \模板\博客\ post_list.html

但是,我不知道如何修复上述路径。 如果你告诉我如何解决这个问题,我很高兴。

1 个答案:

答案 0 :(得分:1)

您的文件结构确切地确认了错误说明:没有名为“blogapp3”的模板目录,因此没有名为“blogapp3 / post_list.html”的模板。

您应该将模板移动到“blogapp3”目录中。