首页 > 解决方案 > 发生模板不存在错误

问题描述

我正在制作 Django app.Django 版本是 1.8 。我在views.py中写道

dir_path = "../static/template/"
if not os.path.exists(dir_path):
    os.makedirs(dir_path)

html_path = dir_path + "test.html"

if os.path.exists(html_path):
    template = loader.get_template(html_path)
    return HttpResponse(template.render(request))

当我运行它时,发生模板不存在错误。但是目录中存在文件,所以我真的不明白为什么会发生这个错误。相对路径不好?我应该如何解决这个问题?

标签: django

解决方案


Django 使用自己的模板引擎,您不必将模板目录设置为静态。

您必须进行TEMPLTES设置。如果需要,只需在设置中添加模板目录。像下面

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            '/your/own/path'
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            # ... some options here ...
        },
    },
]

django 在您的模板目录和基本模板目录中自动动态地找到您的模板(在您的项目和/或应用程序的模板目录中)

在这里阅读 django 模板文档,它会有很大帮助。


推荐阅读