[Django]-Django: Display contents of txt file on the website

11๐Ÿ‘

โœ…

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.

๐Ÿ‘คYannic Hamann

0๐Ÿ‘

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>
๐Ÿ‘คSecane

Leave a comment