我正在 Django 中创建一个返回静态 HTML 页面的 View ,该 View 的代码如下:
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import render_to_response
import codecs
# Basic HTTP response that returns my html index
# To call this view, map it to a URLconf
def index(request):
# When a request is called, return my index.html
html = codecs.open("index.html", "r")
return HttpResponse(html.read())
当我启动 Django 开发时。服务器并导航到我的应用程序,而不是我期望的 index.html
渲染,我在/myapp/ 处遇到 FileNotFoundError 以及
[错误2]没有这样的文件或目录:'index.html'
。我知道 index.html
是与我的 views.py
位于同一目录中的真实文件,并且我还尝试通过打开 debug 进行调试.txt
在同一目录中并返回该内容,但结果相同。当我在同一目录中打开 python shell 并尝试打开同一文件时,它运行顺利。任何见解将不胜感激,因为我完全被难住了。
最佳答案
如果您想从与 view.py 文件相同的目录中打开文件,请使用以下命令:
html = open(os.path.dirname(os.path.realpath(__file__)) + 'index.html', "r")
关于python - 使用编解码器返回 HTML 时 View 中出现 Django FileNotFoundError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40066199/