Django: Display contents of txt file on the website

Question:

I have this in my views.py

def read_file(request):
    f = open('path/text.txt', 'r')
    file_contents = f.read()
    print (file_contents)
    f.close()
    return render(request, "index.html", context)

Urls.py:

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^impala/$', views.people, name='impala'),
]

I am not seeing anything on the website (text.txt file has information).
I also don’t see any output in the terminal and there are no errors.

Asked By: TheNewGuy

||

Answers:

If you have the function read_file in your views.py adjust your urls.py to:

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^test/$', views.read_file, name='test'),
    url(r'^impala/$', views.people, name='impala'),
]

Fix your function based view:

from django.http import HttpResponse

def read_file(request):
    f = open('path/text.txt', 'r')
    file_content = f.read()
    f.close()
    return HttpResponse(file_content, content_type="text/plain")

Spin up up your development server and visit localhost:port/test. You should see the content of test.txt.

If you want to pass the content of the text file to your template.html add it to the context variable and access it in your template with {{ file_content }}.

def read_file(request):
    f = open('path/text.txt', 'r')
    file_content = f.read()
    f.close()
    context = {'file_content': file_content}
    return render(request, "index.html", context)

Keep in mind that a web server like nginx or apache would normally take care of serving static files for performance reasons.

Answered By: Yannic Hamann

you can pass content of your file as a string to your html template

def read_file(request):
    f = open('path/text.txt', 'r')
    file_contents = f.read()
    f.close()
    args = {'result' : file_contents }
    return render(request, "index.html", context, args)
#######################index.html


   
<HTML>
 ...
   <BODY>
      <P>{{ result }} </p>
   </BODY>
</HTML>
Answered By: Secane
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.