python - 姜戈;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),
]
解决方案
您的模板有不同的路径(缺少“博客/”):
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 <...>
推荐阅读
- r - 编织我的 r markdown 文档时遇到问题
- .htaccess - 使用 htaccess 将 https 重定向到 http
- python - IndexError:仅在使用 SSH 时列出索引超出范围错误消息
- javascript - 使用 Interact JS 调整大小
- android - Ionic 3 Livereload 无法在 Android 设备上运行
- python-3.x - 在python中打印unicode字符
- react-native - Native Base Toast 在实时模式下不起作用
- django - 获取用户表中注册的不同用户名并使用表单集将其保存为外键
- angular-material - 带有角材料和 flexLayout 的仪表板
- python - 从一维数组中的值切片二维数组