Django: Display contents of txt file on the website

14,736

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.

Share:
14,736
TheNewGuy
Author by

TheNewGuy

Updated on June 30, 2022

Comments

  • TheNewGuy
    TheNewGuy almost 2 years

    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 am not seeing any print output in nohup. No errors

  • TheNewGuy
    TheNewGuy about 6 years
    I succeed with localhost:port/test, I do see the text from my file. trying to get it to show up on the main site
  • Yannic Hamann
    Yannic Hamann about 6 years
    What you mean by main site? Do you want to change the url or wire it to your template?
  • TheNewGuy
    TheNewGuy about 6 years
    Sorry, i meant wire it to my template. Still unable to do that, I have the variable in my template but nothing is showing
  • Yannic Hamann
    Yannic Hamann about 6 years
    You can add {% debug %} to your template to view the content of the current context.
  • Mohamed Daaniyaal
    Mohamed Daaniyaal about 6 years
    @YannicHamann when i added {% debug %} i get this error . {'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'ERROR': 40, 'INFO': 20, 'SUCCESS': 25, 'WARNING': 30}, 'csrf_token': ._get_val at 0x10dd11268>>,