首页 > 解决方案 > 姜戈;TemplateDoesNotExist 错误 - 博客应用程序

问题描述

我试图按照在线教程创建一个博客应用程序,但在加载一些模板时遇到了困难。

似乎找不到 blog/templates/blog/... 中的模板。

http://127.0.0.1:8000/blog/页面加载正常。下面包括来自 settings.py、views.py 和 urls.py 文件的当前代码。

设置.py

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

... 

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # third party installs go here.
    'products',
    'pages',
    'blog',
]

...

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',
            ],
        },
    },
]

视图.py

from django.shortcuts import render, get_object_or_404
from django.http import Http404

# Create your views here.

from .models import BlogPost
def blog_post_list_view(request):
    qs = BlogPost.objects.all()  # queryset -> list of python objects
    template_name = 'blog/blog_post_list.html'
    context = {"object_list": qs}
    return render(request, template_name, context)


def blog_post_create_view(request):
    # create objects
    #template_name = 'blog/blog_post_create.html'
    context = {"form": None}
    return render(request, "blog/blog_post_create.html", context)


def blog_post_detail_view(request, slug):
    obj = get_object_or_404(BlogPost, slug=slug)
    template_name = 'blog_post_detail.html'
    context = {"object": obj}
    return render(request, template_name, context)


def blog_post_update_view(request, slug):
    obj = get_object_or_404(BlogPost, slug=slug)
    template_name = 'blog_post_update.html'
    context = {"object": obj, 'form': None}
    return render(request, template_name, context)


def blog_post_delete_view(request, slug):
    obj = get_object_or_404(BlogPost, slug=slug)
    template_name = 'blog_post_delete.html'
    context = {"object": obj}
    return render(request, template_name, context)

网址.py

from django.urls import path
from .views import (
    blog_post_create_view,
    blog_post_detail_view,
    blog_post_list_view,
)

app_name = 'blog'
urlpatterns = [
    path('<str:slug>/', blog_post_detail_view),
    path('', blog_post_list_view),
    path('new-post', blog_post_create_view),
]

标签: pythondjangopython-3.xdjango-templatesdjango-views

解决方案


您的模板有不同的路径(缺少“博客/”):

template_name = 'blog/blog_post_list.html'
template_name = 'blog_post_detail.html'
template_name = 'blog_post_update.html'

您还需要确保您已在此处制作模板:

blog/templates/blog/blog_post_list.html <...>

推荐阅读