TheNewGuy
TheNewGuy

Reputation: 579

Django: Display contents of txt file on the website

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.

Upvotes: 3

Views: 21508

Answers (2)

Secane
Secane

Reputation: 41

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>

Upvotes: 0

Yannic Hamann
Yannic Hamann

Reputation: 5205

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.

Upvotes: 13

Related Questions