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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With