【问题标题】:Template file not found Django找不到模板文件 Django
【发布时间】:2020-07-06 06:14:04
【问题描述】:

我正在尝试通过 Django 创建一个新网站的主页。 我的应用名称是“博客”,主页是 home.html 我去http://127.0.0.1:8000/blog/home/时仍然收到错误模板不存在@

我确保我在 settings.py 中的模板中添加了“博客”,并且我在主目录以及 blog/templates/blog/home.html 中添加了文件夹模板

myproject/blog/views.py

from django.shortcuts import render
from django.http import HttpResponse


def home(request):
    return render(request, 'blog/home.html')

我的项目/博客/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('home/', views.home, name='home'),

]

我的项目/settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    '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',
            ],

我的项目/urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('blog/', include('blog.urls')),
]

您是否在我的代码中看到导致问题的任何内容?我在 blog/views.py 中收到“找不到模板文件'博客'”的消息

返回渲染(请求,'blog/home.html')

【问题讨论】:

    标签: python django django-models django-views django-templates


    【解决方案1】:

    你做错了。您需要仔细阅读 Django 文档并尝试理解您阅读的内容并逐步实现相同的内容。 您必须点击的网址是

    http://127.0.0.1:8000/blog/home/
    

    home.html 将在此 url 上呈现。 您没有将 html 页面名称放在 url 中

    【讨论】:

    • 感谢您的意见。但是,即使我在没有 html 的情况下输入,我收到的模板也不存在。错误信息也出现在 blog/views.py
    • 您将 home.html 文件保存在哪里?
    • 根据您的代码,它必须在 templates/blog/home.html 中,其中 templates 目录与 views.py 处于同一级别
    • 谢谢,当 home.html 模板必须放在 myproject/blog/templates/blog/home.html 中时,我已将它放在 myproject/blog/templates/home.html 中
    【解决方案2】:

    我也一直在寻找答案,我尝试了所有方法,但这在我的 Windows 机器上对我有用。在os.path.join(BASE_DIR, 'templates') 中的“模板”之前添加'r' 看起来像这样os.path.join(BASE_DIR, r'templates') 解决了错误问题。此外,我的模板目录位于父应用程序和子应用程序旁边的项目根目录中。

    【讨论】:

    • 当存在 'r' 或 'R' 前缀时,反斜杠后面的字符将原样包含在字符串中,并且所有反斜杠都保留在字符串中。你想用'r'前缀来达到什么目的?
    猜你喜欢
    • 2018-01-02
    • 2012-07-10
    • 2015-03-14
    • 2020-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多