3

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.

2
  • You should give an absolute path to the file. Commented Oct 16, 2016 at 2:39
  • Using os.path.abspath("index.html"), assuming I already imported os, you mean? Because I tried, and I get the same error. Commented Oct 16, 2016 at 2:42

2 Answers 2

4

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")
Sign up to request clarification or add additional context in comments.

Comments

0

To further explain what I just found out why open doesn't simply work. The path you specify within open is relative to the location of the script executing the code. Therefore it works when you execute the file itself but not if Django executes it. This is because Django runs in a different directory.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.