【问题标题】:Template file path模板文件路径
【发布时间】:2017-12-07 12:47:13
【问题描述】:

我试图在我的 django 项目中打开并阅读这个 html 文件,但是我得到了这个 [Errno 2] 没有这样的文件或目录:'test.html'。

html = 'test.html'
open_html = open(html, 'r')
soup =  BeautifulSoup(open_html, "html5lib")
open_html.close()

但模板路径在渲染时似乎工作正常

template = 'test.html'
context = {
}
return render(request, template, context)

TEMPLATES = [
        'DIRS': [os.path.join(BASE_DIR, "templates")],
]

我知道我的模板应该放在我的应用文件夹中,但是我喜欢在开发和调试时将它们保存在一个文件夹中。

【问题讨论】:

  • html = 'test.html' open_html = open(html, 'r') 此代码不采用完整路径。 html 只有文件名 test.html 但 BeautifulSoup 需要完整路径。而不是 html = 'test.html' 这提供了文件的实际路径。

标签: django django-templates


【解决方案1】:

因为你试图从模板访问文件所以你需要添加完整路径

尝试以下解决方案

from your_project_name.settings import BASE_DIR
path = os.path.join(BASE_DIR+'templates/', 'test.html')
open_html = open(path, 'r')
soup =  BeautifulSoup(open_html, "html5lib")
open_html.close()

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2017-11-15
    • 2018-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多