使用编解码器返回HTML时视图中的Django FileNotFoundError

问题描述 投票:1回答:1

我在Django中创建一个返回静态HTML页面的视图,该视图的代码如下:

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渲染,我遇到了FileNotFoundError at /myapp/以及[Errno 2] No such file or directory: 'index.html'。我知道index.html是与myviews.py在同一目录中的真实文件,我也尝试通过在同一目录中打开debug.txt并返回它来调试,但结果相同。当我在同一目录中打开python shell并尝试打开同一个文件时,它可以毫无障碍地工作。任何见解都会受到赞赏,因为我一直都很难过。

python html django http web-deployment
1个回答
0
投票

如果要从与view.py文件相同的目录中打开文件,请使用以下命令:

html = open(os.path.dirname(os.path.realpath(__file__)) + 'index.html', "r")
© www.soinside.com 2019 - 2024. All rights reserved.