【问题标题】:Django: Passing a static html file into view produce TemplateDoesNotExist errorDjango:将静态 html 文件传递​​到视图中会产生 TemplateDoesNotExist 错误
【发布时间】:2018-02-03 00:33:13
【问题描述】:

我有一个 django 应用程序和一个主页视图,我想在主页上使用静态 html 文件。我的文件结构是这样的:

project/
  stats (this is my app)/
    urls.py
    views.py
    stats.html
    (other files here)

在我的views.py中我有以下代码:

from django.shortcuts import render_to_response

def index(request):
    return render_to_response('stats.html')

当我运行网址时,我只有索引页。我转到统计页面并收到TemplateDoesNotExist 错误。寻找答案我尝试将stats/stats.html 用于路径,但我仍然遇到相同的错误。这样做的正确方法是什么?

【问题讨论】:

标签: python html django templates views


【解决方案1】:

在您的项目目录中,添加一个名为“templates”的目录,并在模板目录中创建“stats”目录。将您的 HTML 文件放在 stats 目录中。

然后从

更改底部的设置文件
TEMPLATE_DIRS = (

    os.path.join(SETTINGS_PATH, 'templates'),

)

TEMPLATE_DIRS = (

    os.path.join(BASE_PATH, 'templates'),

)

【讨论】:

  • 如何让 django 识别模板目录?我将路径作为 TEMPLATE_DIRS 放入我的 settings.py 中,但 django 说它使用了C:\Python36-32\lib\site packages\django\contrib\admin\templates\stats.html 的默认模板路径。我该怎么做才能重定向搜索?
  • 分享您的设置文件。也看看这个。 stackoverflow.com/questions/3038459/django-template-path
  • 更新了我的答案以更适合你
  • 由于某种原因它拒绝识别目录。是否有一些我没有完成的迁移?
  • 不,您还需要更新已安装的应用程序。只需将一个项目添加到统计信息列表中...'stats' 就这么简单
【解决方案2】:

你可以这样安排你的项目

project/
    stats (this is my app)/
        urls.py
        views.py
        stats.html
        templates/
            stats/
                stats.html

在你的views.py中,这样写:

def index(request):
    return render_to_response('stats/stats.html')

确保 settings.py 的 INSTALLED_APPS 列表中有“stats”。

【讨论】:

    猜你喜欢
    • 2020-09-08
    • 2016-12-10
    • 2021-10-19
    • 2016-06-24
    • 2015-06-19
    • 1970-01-01
    • 1970-01-01
    • 2011-06-23
    • 2017-03-05
    相关资源
    最近更新 更多