Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a text file from within Django view function?

Tags:

python

django

I have the following code in one of my view functions:

def results(request):
    data_file = open('data.txt', 'r')       
    data = data_file.read()
    context = {'rooms': data}
    return render(request, 'javascript/results.html',context)

The file 'data.txt' is located in the same folder as my "views.py".

However, I am getting "FileNotFoundError at /results" error.

My 'results.html' looks like this:

<p> {{ rooms }}</p>

What is the correct way to pass data from a text file to a Django view function, and then display the data in the template? Should I use static files instead?

like image 344
barciewicz Avatar asked Mar 26 '26 02:03

barciewicz


1 Answers

Try giving the full path to the text file.

EX:

import os

def results(request):
    module_dir = os.path.dirname(__file__)  
    file_path = os.path.join(module_dir, 'data.txt')   #full path to text.
    data_file = open(file_path , 'r')       
    data = data_file.read()
    context = {'rooms': data}
    return render(request, 'javascript/results.html',context)
like image 69
Rakesh Avatar answered Mar 27 '26 14:03

Rakesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!