I am creating a view in Django that returns a static HTML page, and my code for that view is as follows:
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())
When I fire up the Django dev. server and navigate to my app, instead of the rendering of index.html
that I expect, I am confronted with a FileNotFoundError at /myapp/
as well as [Errno 2] No such file or directory: 'index.html'
. I know for a fact that index.html
is a real file in the same directory as myviews.py
, and I have also tried debugging by opening a debug.txt
in the same directory and returning that, but with the same result. When I open the python shell in the same directory and try to open the same file, it works without a hitch. Any insight would be appreciated, as I am thouroughly stumped.
If you want to open a file from the same directory as your view.py file, use the following:
html = open(os.path.dirname(os.path.realpath(__file__)) + 'index.html', "r")