3

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?

2 Answers 2

9

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)
Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't work with python3.
0
def result(request)
    emails = []
    module_dir = os.path.dirname(__file__)
    file_path = os.path.join(module_dir, 'disposable.txt')
    disposable_mails = open(file_path, 'r+')
    for disposable_mail in disposable_mails:
        emails.append(disposable_mail.rstrip())

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.